Apache FOP: How to set base URL for accessing external resource using relative path - apache-fop

In my .xsl file I am using external graphics like this
<fo:external-graphic width="90pt" height="29pt" src="url(xsl/logo.jpg)"/>
But image is not getting loaded in the generated PDF and I get this error in console.
[ERROR] Error while creating area : Error with image URL: xsl\logo.jpg (The system cannotfind the path specified) and no base URL is specified
How do I solve this issue? I guess setting the base URL will do. But how to set the base URL? Please help.

I got a solution from this link
http://groups.yahoo.com/group/XSL-FO/message/6116
set base dir using Java code
ServletContext servletContext = getServletConfig().getServletContext();
String appPath = servletContext.getRealPath(""); //root of web app
org.apache.fop.configuration.Configuration.put("baseDir",appPath);
This worked for me.
Please post if you know any better solution.

I am using Apache FOP 1.1 Ver.
fopFactory = FopFactory.newInstance();
// for image base URL : images from Resource path of project
String serverPath = request.getSession().getServletContext().getRealPath("/");
fopFactory.setBaseURL(serverPath);
// for fonts base URL : .ttf from Resource path of project
fopFactory.getFontManager().setFontBaseURL(serverPath);
I added all images and required font font files in resource director of my project.
It is working fine for me.
Thank you

I had the same problem and this only works for me in the version 0.95 of fop.
SetBaseUrl is ignored in version 1.0

Solution for versions 1.0, 1.1 :
In fop 1.0 and 1.1 method setBaseURL() does not work correctly with local files, so you can use method setURIResolveri and write your implementation of interface URIResolver.
1.Add in uses
import javax.xml.transform.URIResolver;
2.Add in mainClass
private static class LocalResolver implements URIResolver {
private String BaseFolder;
#Override
public Source resolve(String href, String base) throws TransformerException {
File f = new File(BaseFolder + "\\" + href);
if (f.exists())
return new StreamSource(f);
else
throw new TransformerException("File " + f.getAbsolutePath() +" not found!");
}
public LocalResolver(String BaseFolder) {
this.BaseFolder = BaseFolder;
}
}
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
3.Add before call transformer.transform(src, res) this:
fop.getUserAgent().setURIResolver(new LocalResolver("C:\\Users\\photon\\Downloads\\fop-1.1-bin\\fop-1.1"));

Related

How to display local image as well as resources image in .Net MAUI Blazor

In .Net MAUI Blazor I can use an img tag to display an image from wwwroot folder. But how to display an image from the device's internal storage? And how to display images from application resources?
From Internal storage
We can read it into bytes and convert it to base64 string , then show on img tag .
Giving that we've put an image called dog.png in FileSystem.CacheDirectory folder.
Sample code
#if (imageSource is not null)
{
<div>
<img src="#imageSource" width="200" height="200" />
</div>
}
#code {
private string? imageSource;
protected override void OnInitialized()
{
var newFile = Path.Combine(FileSystem.CacheDirectory, "dog.png");
var imageBytes = File.ReadAllBytes(newFile);
imageSource = Convert.ToBase64String(imageBytes);
imageSource = string.Format("data:image/png;base64,{0}", imageSource);
}
}
To display from resource, see … Blazor Hybrid static Files / .Net Maui:
Add file to project, in a folder named Resources/Raw.
Make sure file / Properties / Build Action = MauiAsset.
Create a razor component that:
Calls Microsoft.Maui.Storage.FileSystem.OpenAppPackageFileAsync to obtain a Stream for the resource.
Reads the Stream with a StreamReader.
Calls StreamReader.ReadToEndAsync to read the file.
Example razor code (from that link):
#page "/static-asset-example"
#using System.IO
#using Microsoft.Extensions.Logging
#using Microsoft.Maui.Storage
#inject ILogger<StaticAssetExample> Logger
<h1>Static Asset Example</h1>
<p>#dataResourceText</p>
#code {
public string dataResourceText = "Loading resource ...";
protected override async Task OnInitializedAsync()
{
try
{
using var stream =
await FileSystem.OpenAppPackageFileAsync("Data.txt");
using var reader = new StreamReader(stream);
dataResourceText = await reader.ReadToEndAsync();
}
catch (FileNotFoundException ex)
{
dataResourceText = "Data file not found.";
Logger.LogError(ex, "'Resource/Raw/Data.txt' not found.");
}
}
}
To access local file (not an asset in resources) from razor code, you’ll need a service that given the file name (or relative path), returns the file contents as a stream.
I’m not finding a doc saying how to do that for Maui, then inject that into razor code.
Such a service would use .Net File System Helpers to access the file. This would be similar to the MauiAsset example above, but using one of the path helpers, NOT calling OpenAppPackageFileAsync.
TBD - someone give reference link or example?
From my research :
You can actually get the path of the wwwroot folder in the razor application with : AppDomain.CurrentDomain.BaseDirectory.
In windows you can add files in this folder that will be accessible from the Blazor HTML. However, in Android the wwwroot folder is embeded in the app and will not be accessible (AppDomain.CurrentDomain.BaseDirectory return a empty folder).
After looking on the .NET MAUI github repo in the BlazorWebView class I found :
public virtual IFileProvider CreateFileProvider(string contentRootDir)
{
// Call into the platform-specific code to get that platform's asset file provider
return ((BlazorWebViewHandler)(Handler!)).CreateFileProvider(contentRootDir);
}
Which can be used to pass files to Blazor. For exemple if you want to make accessible all the files from the AppDataDirectory :
public class CustomFilesBlazorWebView : BlazorWebView
{
public override IFileProvider CreateFileProvider(string contentRootDir)
{
var lPhysicalFiles = new PhysicalFileProvider(FileSystem.Current.AppDataDirectory);
return new CompositeFileProvider(lPhysicalFiles, base.CreateFileProvider(contentRootDir));
}
}
Then in MainPage.xaml :
<local:CustomFilesBlazorWebView HostPage="wwwroot/index.html" x:Name="WebView">
<BlazorWebView.RootComponents>
<RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
</BlazorWebView.RootComponents>
</local:CustomFilesBlazorWebView>
For exemple if in AppDataDirectory you have a file images/user.png in any Blazor component you can use :
<img src="images/user.png" />
I solved in this way.
Add the png image to Resources\Raw and set to MauiAsset compilation type
Check the project file to avoid that the image is excluded via ItemGroup-> None Remove. In this case delete the ItemGroup related to the image.
After this:
In my razor component HTML
<img src="#imageSource">
In the code part:
private string? imageSource;
protected override async Task OnInitializedAsync()
{
try
{
using var stream =
await FileSystem.OpenAppPackageFileAsync("testimage.png");
using var reader = new StreamReader(stream);
byte[] result;
using (var streamReader = new MemoryStream())
{
stream.CopyTo(streamReader);
result = streamReader.ToArray();
}
imageSource = Convert.ToBase64String(result);
imageSource = string.Format("data:image/png;base64,{0}", imageSource);
}
catch (Exception ex)
{
//log error
}
}

How to create a builtin file and folder in custom eclipse plugin

I am developing an Eclipse plugin which need to be shipped with builtin ant build file. Its working when I am running the project. However, when I am exporting the plugin and deploying the exported plugin in another eclipse, the ant build file is not getting generated. My suspect is that in the runtime, the source of the ant build file is not accessed. Any pointer how to solve the issue? Here is the code :
private void createAntFile(IProject project, Properties properties) throws CoreException, IOException {
InputStream antFileInputStream =null;
try {
String antFileName = properties.getProperty("name.ant.file");
String antFilePath = properties.getProperty("path.ant.file");
IFile file = project.getFile(antFileName);
antFileInputStream = Activator.getDefault().getBundle().getEntry(antFilePath).openStream();
file.create(antFileInputStream, false, null);
antFileInputStream.close();
}finally{
if(antFileInputStream!=null){
try {
antFileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
name.ant.file=build.xml
path.ant.file=src/weblogic/ant/build.xml
The source build file I am hard coding in the path src/weblogic/ant/build.xml
Edit:
Here is the code to create builtin folders:
private void createWeblogicTemplate(IProject project, Properties properties) throws IOException, CoreException {
String weblogicTemplateSourcePath = properties.getProperty("path.weblogic.template.source");
Path path = new Path(weblogicTemplateSourcePath);
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileURL = FileLocator.find(bundle, path, null);
String filePath = FileLocator.resolve(fileURL).getPath();
System.out.println(filePath);
File sourceFile = new File(filePath);
String weblogicTemplateTargetPath = properties.getProperty("path.weblogic.template.target");
IFolder folder = project.getFolder(weblogicTemplateTargetPath);
copyFolder(sourceFile,folder,project,properties);
}
The line System.out.println(filePath) is printing path as
/C:/Users//Desktop/eclipse-rcp-luna-SR2-win32-x86_64/eclipse/../../../workspace-plugin/weblogic/resources/weblogictemplate/
So, locally its working. However, its not working when I deploy the pluin in some other eclipse. Any pointer how to create builtin folders?
You appear to be expecting the src/weblogic/ant/ directory to be included in the exported plugin jar - the src directory is not normally included in the plugin jar.
Put resources you want to include in the plugin in a separate directory (such as resources) and include that directory in the plugin build.properties so that it is included in the exported plugin jar.

Plug-In that Converted Note entity pre-existing attachment XML file into new .MMP file

strong text [Plugin error at Note entity][1]
[1]: http://i.stack.imgur.com/hRIi9.png
Hi,Anyone resolved my issue i got a Plug-in error which i worked at Update of "Note" entity.Basically i want a Plugin which converted pre-exiting Note attachment XML file into new .MMP extension file with the same name.
I have done following procedure firstly i created a "Converter_Code.cs" dll which contains Convert() method that converted XML file to .MMP file here is the constructor of the class.
public Converter(string xml, string defaultMapFileName, bool isForWeb)
{
Xml = xml;
DefaultMapFileName = defaultMapFileName;
Result = Environment.NewLine;
IsForWeb = isForWeb;
IsMapConverted = false;
ResultFolder = CreateResultFolder(MmcGlobal.ResultFolder);
}
In ConvertPlugin.cs Plug-in class firstly i retrieved Note entity attachment XML file in a string using following method in
IPluginExecutionContext context =(IPluginExecutionContext)serviceProvider.
GetService (typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory= (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService
(context.UserId);
if (context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
var annotationid = entity.GetAttributeValue<Guid>("annotationid");
if (entity.LogicalName != "annotation")
{
return;
}
else
{
try
{
//retrieve annotation file
QueryExpression Notes = new QueryExpression { EntityName ="annotation"
,ColumnSet = new ColumnSet("filename", "subject", "annotationid",
"documentbody") };
Notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal,
annotationid);
EntityCollection NotesRetrieve = service.RetrieveMultiple(Notes);
if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
{
{
//converting document body content to bytes
byte[] fill = Convert.FromBase64String(NotesRetrieve.Entities[0]
.Attributes["documentbody"].ToString());
//Converting to String
string content = System.Text.Encoding.UTF8.GetString(fill);
Converter objConverter = new Converter(content, "TestMap", true);
objConverter.Convert();
}
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("something is going wrong");
}
}
}
}
and than A string is passed to "Converter" constructor as a parameter.
finally i merged all dll using ILMerge following method:
ilmerge /out:NewConvertPlugin.dll ConvertPlugin.dll Converter_Code.dll
and NewConvertPlugin is registered successfully but while its working its generate following error:
Unexpected exception from plug-in (Execute): ConverterPlugin.Class1: System.Security.SecurityException: That assembly does not allow partially trusted callers.
i also debug the plugin using Error-log but its not worked so i could not get a reason whats going wrong.
The error is caused by the library you merged inside your plugin.
First of all you are using CRM Online (from your screenshot) and with CRM Online you can use only register plugins inside sandbox.
Sandbox means that your plugins are limited and they run in a partial-trust environment.
You merged an external library that requires full-trust permissions, so your plugin can't work and this is the reason of your error.
Because you are in CRM Online, or you find another library (the Converter) that requires only partial-trust, hoping that the merge process will work, or you include (if you have it) the source code of the converter library directly inside your plugin.

How to get entire classpath of the modules added to wildfly server

I have tried below snippet
String path = System.getProperty("java.class.path");
I get
../wildfly-8.2.0.Final/jboss-modules.jar
String modulepath = System.getProperty("jboss.module.path");
// ../wildfly-8.2.0.Final/jboss-modules.jar
and not the ones which i have added in modules
when i try
StringBuffer buffer = new StringBuffer();
for (URL url :
((URLClassLoader) (Thread.currentThread()
.getContextClassLoader())).getURLs()) {
buffer.append(new File(url.getPath()));
buffer.append(System.getProperty("path.separator"));
}
Getting :
java.lang.ClassCastException: org.jboss.modules.ModuleClassLoader cannot be cast to java.net.URLClassLoader
Use getResourceAsStream on your application class path which is using the same class loader as your app.

GWT Window redirection problem

Hi I have this code in my gwt app which purpose is to chage to URL as follows:
public void goToSignUpPage(boolean isDeployed) {
String url = (isDeployed == true ? "signup.html" : "signup.html?gwt.codesvr=127.0.0.1:9997");
Window.Location.replace(url);
However what happens it redirects into this URL:
http://127.0.0.1:8888/mygwtapp/signup.html?gwt.codesvr=127.0.0.1:9997
Where the working URL is this:
http://127.0.0.1:8888/signup.html?gwt.codesvr=127.0.0.1:9997
BTW, mygwtapp is the gwt module named defined in MyGwtApp.gwt.xml
<module rename-to='mygwtapp'>
Any ideas why the URL is appended by the gwt module name? Any way to fix this?
All you needed was to add in GWT.getHostPageBaseURL() to get the full URL for your web application without it appending to the module name.
Try this out:
public void goToSignUpPage() {
String url = GWT.getHostPageBaseURL() + "signup.html";
if(!GWT.isProdMode()) {
Window.alert("We are in development mode!");
url += "?gwt.codesvr=127.0.0.1:9997";
}
Window.Location.replace(url);
}
I've also removed your parameter "isDeployed" and replaced it with GWT.isProdMode() within the method to check if you're in production or development mode.
With a paramater:
public void goToSignUpPage(Boolean isDeployed) {
String url = GWT.getHostPageBaseURL() + "signup.html";
if(!isDeployed) {
url += "?gwt.codesvr=127.0.0.1:9997";
}
Window.Location.replace(url);
}
Hope this helps!