Set FopFactoryBuilder baseURI to jar classpath - apache-fop

I'm upgrading an Apache FOP 1.0 project to Apache FOP 2.1. In this project, all necessary files are packaged within the jar file.
I've added the new FopFactoryBuilder to generate a FopFactory
FopFactoryBuilder builder = new FopFactoryBuilder(new File(".").toURI());
builder = builder.setConfiguration(config);
fopFactory = builder.build();
but all my resouces are loaded from the relative path on my file system, not from the jar. How can I set the baseURI to the jar's classpath?
Thanks

We also used FOP 2.1 and want to achieve, that images inside jars-classpath will be found. Our tested and used solution is the following:
Create your own ResourceResolver
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import org.apache.fop.apps.io.ResourceResolverFactory;
import org.apache.xmlgraphics.io.Resource;
import org.apache.xmlgraphics.io.ResourceResolver;
public class ClasspathResolverURIAdapter implements ResourceResolver {
private final ResourceResolver wrapped;
public ClasspathResolverURIAdapter() {
this.wrapped = ResourceResolverFactory.createDefaultResourceResolver();
}
#Override
public Resource getResource(URI uri) throws IOException {
if (uri.getScheme().equals("classpath")) {
URL url = getClass().getClassLoader().getResource(uri.getSchemeSpecificPart());
return new Resource(url.openStream());
} else {
return wrapped.getResource(uri);
}
}
#Override
public OutputStream getOutputStream(URI uri) throws IOException {
return wrapped.getOutputStream(uri);
}
}
Create the FOPBuilderFactory with your Resolver
FopFactoryBuilder fopBuilder = new FopFactoryBuilder(new File(".").toURI(), new ClasspathResolverURIAdapter());
Finally address your image
<fo:external-graphic src="classpath:com/mypackage/image.jpg" />
Because you use our own Resolver it is possible to do every lookup which you want.

By specifying the URL as a classpath URL like:
<fo:external-graphic src="classpath:fop/images/myimage.jpg"/>
In this example the file is a resource in the resource-package fop.images but the actual file gets later packed to some entirely different place inside the JAR, which is - however - part of the classpath, so the lookup as above works.

Related

How to replace sling:resourceType value in bulk using query or script

How to replace sling:resourceType value in bulk using Query and Scipt.
For example I want to change sling:resourceType value
from app/component/linkButton to app/component/content/linkbutton1.
The component is being used on 20 pages, and I want change it using query rather than manually on each page.
the best choice for the purpose is groovy console .
Bellow script which do the job:
import javax.jcr.Node
getNode('/content/').recurse { resourceNode ->
if (resourceNode.hasProperty('sling:resourceType')) {
final def resourceType = resourceNode.getProperty('sling:resourceType').string
if (resourceType.equals('OLD_RESOURCE_TYPE')) {
println "changing " + resourceNode.path
resourceNode.setProperty('sling:resourceType', 'NEW_RESOURCE_TYPE')
resourceNode.save();
}
}
}
You can use the ACS AEM Tools open source project which includes AEM Fiddle. AEM Fiddle allows you to run scripts directly on the AEM instance without have to build.
If you use AEM Fiddle, navigate to http://localhost:4502/miscadmin#/etc/acs-tools/aem-fiddle, click the plus sign in the top right and select .java. Insert this code and run. Make sure you update the query's path.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.jcr.query.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
public class fiddle extends SlingAllMethodsServlet {
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
ResourceResolver resolver = null;
out.println("starting...");
try {
resolver = request.getResourceResolver();
if (resolver != null) {
Iterator<Resource> resources = resolver.findResources("/jcr:root/content/mysite//*[#sling:resourceType='app/component/linkButton']", Query.XPATH);
while (resources.hasNext()) {
Resource resource = resources.next();
ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
properties.put("sling:resourceType", "app/component/linkButton1");
resolver.commit();
out.println(resource.getPath());
}
}
} catch(Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace(out);
} finally {
if (resolver != null && resolver.isLive()) {
resolver.close();
resolver = null;
}
}
out.println("...finished");
}
}
If you'd rather use JSP as you've stated, the code is the same:
<%#include file="/libs/foundation/global.jsp"%><%
%><%#page session="false" contentType="text/html; charset=utf-8"
pageEncoding="UTF-8"
import="org.apache.sling.api.resource.*,
java.util.*,
javax.jcr.*,
com.day.cq.search.*,
com.day.cq.wcm.api.*,
com.day.cq.dam.api.*,
javax.jcr.query.Query,
org.apache.sling.api.resource.ModifiableValueMap"%><%
Iterator<Resource> resources = resourceResolver.findResources("/jcr:root/content/mysite//*[#sling:resourceType='app/component/linkButton']", Query.XPATH);
while (resources.hasNext()) {
Resource current = resources.next();
ModifiableValueMap props = current.adaptTo(ModifiableValueMap.class);
props.put("sling:resourceType", "app/component/linkButton1");
resourceResolver.commit();
%>
<%=current.getPath()%>
<%
}
%>
Another dirty method, but worked for me. :)
Package the path and download the zip file.
Extract to a folder.
Based on your operating system,
If using Windows, use Notepad++ to find an replace in all files under directory with your search pattern.
If linux, use find or sed commands to replace all occurrences inside a director
How about AEM ACS TOOLS?
It is bulk updating tool for sling:resourceType or cq:Template.
Click here for the article on Getting Started
Click here for the Github Repo
Good Luck...
You can also have a look at sling pipes.
https://sling.apache.org/documentation/bundles/sling-pipes.html
this is the perfect solution for your problem

de.hybris.eventtracking.model.events.AbstractTrackingEvent cannot be resolved to a type

I just finished configuring hybris and tried to set up the eclipse project. As per guidelines in the wiki.hybris, I imported all the extensions into the eclipse project. When I try into build and clean, I get more than 3000 compiler errors. One of the errors is the class AbstractTrackingEvent cannot be resolved to a type. I looked for the particular class in the project folder. I could not find the folder events under de.hybris.eventtracking.model, which is the cause of the issue.
Am I missing anything while importing the project? There are many such type of issues in my eclipse project. Please let me know how to fix it. I have attached the screenshot for reference.
Note: I am using hybris-commerce-suite 5.7.0.8
As requested, I am adding the source code.
package de.hybris.eventtracking.services.populators;
import de.hybris.eventtracking.model.events.AbstractTrackingEvent;
import de.hybris.eventtracking.services.constants.TrackingEventJsonFields;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* #author stevo.slavic
*
*/
public abstract class AbstractTrackingEventGenericPopulator implements
GenericPopulator<Map<String, Object>, AbstractTrackingEvent>
{
private final ObjectMapper mapper;
public AbstractTrackingEventGenericPopulator(final ObjectMapper mapper)
{
this.mapper = mapper;
}
public ObjectMapper getMapper()
{
return mapper;
}
protected Map<String, Object> getPageScopedCvar(final Map<String, Object> trackingEventData)
{
final String cvar = (String) trackingEventData.get(TrackingEventJsonFields.COMMON_CVAR_PAGE.getKey());
Map<String, Object> customVariablesPageScoped = null;
if (StringUtils.isNotBlank(cvar))
{
try
{
customVariablesPageScoped = getMapper().readValue(cvar, Map.class);
}
catch (final IOException e)
{
throw new ConversionException("Error extracting custom page scoped variables from: " + cvar, e);
}
}
return customVariablesPageScoped;
}
}
"As per guidelines in the wiki.hybris, I imported all the extensions into the eclipse project."
I don't think the guidelines tell you this. Basically, you want the projects loaded to be the same as those defined in your localextensions.xml and their dependencies. The reason you can't see those is they are not built.
Ensure you have run 'ant build' successfully, refresh the platform project, remove any extensions from your workspace that are not needed for your project, and clean and build in eclipse.
Make sure you have provided the project dependencies in each project by checking their individual extensioninfo.xml files as shown in below image.
Also sometimes dependent libraries are not imported properly check for those too.

JasperReports Library and MongoDB

So here is my source code :
import com.jaspersoft.mongodb.MongoDbConnection;
import com.jaspersoft.mongodb.MongoDbDataSource;
import java.io.File;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
public class Generate {
public static void main(String[] args) throws UnknownHostException {
try {
// - Connexion à la base
String mongoURI = "mongodb://localhost/test";
MongoDbConnection connection = null;
Map<String, Object> parameters = new HashMap<String, Object>();
try {
connection = new MongoDbConnection(mongoURI,null,null);
parameters.put(MongoDbDataSource.CONNECTION, connection);
JasperDesign jasperDesign = JRXmlLoader.load("/home/test/gocoffee.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
File jasperFile;
jasperFile = new File("/home/test/MongoDbReport.jasper");
JasperCompileManager.compileReportToFile("/home/test/gocoffee.jrxml", "/home/test/MongoDbReport.jasper");
JasperFillManager.fillReportToFile("/home/test/MongoDbReport.jasper", parameters);
JasperExportManager.exportReportToPdfFile("/home/test/MongoDbReport.jrprint");
} catch(Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Mongo is running.
I have gocoffee.jrxml in my folder named "test" and when I compile I get BUILD SUCCESSFUL but no pdf file appears in my "test" folder.
Interesting fact : if i do a
System.out.print("123");
after this line :
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
It doesn't work.
(I just fixed this error before this one. Maybe its related)
Thanks !
Ps: mdahlman you are awesome
A report working in iReport but failing in your application that uses JasperReports probably means that you're missing the query executer. Create jasperreports.properties (or edit your existing one), make sure it's on the classpath, and add this line:
net.sf.jasperreports.query.executer.factory.MongoDbQuery=com.jaspersoft.mongodb.MongoDbQueryExecuterFactory
Note1: You should look at the working unit test (which uses this idea) in the source that's posted to jasperforge. That really ought to have all that you need.
Note2: We recently figured out that it's a hassle to have to do this, so we updated the connector to have a copy of jasperreports_extension.properties which performs the same role. But then it's included in the connector .jar file, so you don't have to worry about it. That will be posted soon.

How can I use properties taken from a file in the code of an eclipse PDE fragment/plugin project?

I have created an eclipse plugin project and a corresponding fragment project which I use for junit tests.
In the fragment I specify the plugin project as the "Host plugin". Further I specify the following on the build.properties pane:
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
my.properties
where my.properties is a file located at the root of the fragment project. I have then written a test where I try to load the my.properties file like this:
Properties properties = new Properties();
InputStream istream = this.getClass().getClassLoader()
.getResourceAsStream("my.properties");
try {
properties.load(istream);
} catch (IOException e) {
e.printStackTrace();
}
but istream is null and the test fails with a NullPointerException when calling load in the try block.
I have tried to do the same thing in the host plugin and there it works fine. Any ideas about why I can't read resouces in my PDE fragment when using Junit?
Try using Bundle#getEntry. If your plug-in has an Activator, you get a BundleContext object when your plugin is started (use Bundle-ActivationPolicy: lazy in your manifest). You can get the Bundle object from the BundleContext:
public class Activator implements BundleActivator {
private static Bundle bundle;
public static Bundle getBundle() {
return myBundle;
}
public void start(BundleContext context) throws Exception {
bundle = context.getBundle();
}
}
...
URL url = Activator.getBundle().getEntry("my.properties");
InputStream stream = url.openStream();
properties.load(stream);
One problem you MIGHT be having is that
InputStream istream = this.getClass().getClassLoader().
getResourceAsStream("my.properties");
behaves differently in two situations where "this" is located in a different package. Since you did not append "/" to the beginning, java will automatically start looking at the package root instead of the classpath root for the resource. If the code in your plug-in project and your fragment project exist in different packages, you have a problem.
Andrew Niefer has pointed the direction, but the solution is wrong. That is one that works:
1) Add super(); to the your Activator constructor.
2) Put this into the constructor of your plugin:
Properties properties = new Properties();
try {
Bundle bundle=Activator.getDefault().getBundle();
URL url = bundle.getEntry("plugin.properties");
InputStream stream;
stream = url.openStream();
properties.load(stream);
} catch (Exception e) {
e.printStackTrace();
}
And you have functioning "properties".
Explanations:
Doing (1) you will reach all that functionality:
public class Activator implements BundleActivator {
private static Bundle bundle;
public static Bundle getBundle() {
return myBundle;
}
public void start(BundleContext context) throws Exception {
bundle = context.getBundle();
}
}
It is present already in the pre-parent class Plugin. And you simply can't put it into Activator, because getBundle() is final in Plugin.
Notice Activator.getDefault() in (2). Without it bundle is unreachable, it is not static. And if you simply create a new instance of activator, bundle of it will be null.
There is one more way to take a bundle:
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
Only check that Activator.PLUGIN_ID is set to the correct string - as is in the ID field of the Overview page of the plugin. BTW, you should check this Activator.PLUGIN_ID after every change of the plugin ID anyway.

Why am I having trouble accessing a .properties file in a standalone instance of tomcat but not in an eclipse-embedded instance?

I wrote a simple Hello World Servlet in Eclipse containing the following in the doGet method of my HelloWorldServlet.java
PrintWriter writer = response.getWriter();
String hello = PropertyLoader.bundle.getProperty("hello");
writer.append(hello);
writer.flush();
PropertyLoader is a simple class in the same package as the Servlet that does the following:
public class PropertyLoader {
public static final Properties bundle = new Properties();
static {
InputStream stream = null;
URL url = PropertyLoader.class.getResource("/helloSettings.properties");
stream = new FileInputStream(url.getFile());
bundle.load(stream);
}
}//End of class
I placed a file called helloSettings.properties in /WebContent/WEB-IND/classes that contains the following single line of content:
hello=Hello Settings World
When I add Tomcat 6.0 to my project and run it in eclipse it successfully prints
"Hello Settings World" to the web browser.
However when I export the project as a war file and manually place it in
.../Tomcat 6.0/webapps I then get "null" as my result.
Is it a problem with the classpath/classloader configuration? permissions? any of the other configuration files? I know for a fact that the helloSettings.properties file is in the WEB-INF/classes folder.
Any help?
Well, after much browsing I found what seems a "normal" why to do what I'm trying to do:
Instead of...(how I was doing it)
public class PropertyLoader {
public static final Properties bundle = new Properties();
static {
InputStream stream = null;
URL url = PropertyLoader.class.getResource("/helloSettings.properties");
stream = new FileInputStream(url.getFile());
bundle.load(stream);
}
}//End of class
THE FIX
public class PropertyLoader {
public static final Properties bundle = new Properties();
static {
InputStream stream = null;
stream = SBOConstants.class.getResourceAsStream("/sbonline.properties");
bundle.load(stream);
}
}//End of class
I'm modifiying someone else's code so I'm not sure why they did it the other way in the first place... but I guess url.getFile() was my problem and I don't know why.