JasperReports Library and MongoDB - 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.

Related

Drools Creating Rules(DRL) Programatically not working in drools-distribution-6.5.0.Final

I am working on putting some business rules in drool engine.We cannot use KIE workspace UI to author rules.So that is out.
Problem Statement:Create a application(front end angular UI) back end spring boot microservice to author rules.Those authored rules needs to be dynamically refreshed without having to restart the jvm and other micro services which want to use these rules,should use them.For e.g:granting credit or interest rates based dealer credit history ,duration with bank and any new rules which might be designed as per author.I started looking on this and theoretically one could build something like this by using API of drools compiler library.
There is code example here.
for real time refreshing,there is something called KnowledgeAgent.
https://docs.jboss.org/drools/release/5.2.0.Final/drools-guvnor-docs/html/ch09.html
What is the new accepted way of programmatically creating new drools rules in Drools 6?
My problem is I am not able to make this work.Code is running fine but I am not able to see the drl file getting written.In debug mode,I can see string object with proper drl structure.Has anyone encountered this problem before.?
I have seen some examples on github where people have done yoman job to integrate drools in spring boot.I can start with building my service,but I need to be sure that this something which is possible to do
Following code will help you create drool rule using code.It is not recommended way and most of people use kie-web interface to design and modify drool rules.Not sure about how we can modify already created .drl files.But this has given me start.Going
package com.sample.model;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.drools.compiler.lang.DrlDumper;
import org.drools.compiler.lang.api.DescrFactory;
import org.drools.compiler.lang.api.PackageDescrBuilder;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
//#SuppressWarnings("restriction")
public class GenerateRule {
public static void main(String[] args) {
// TODO Auto-generated method stub
KieContainer container=build(KieServices.Factory.get());
System.out.println(container.getReleaseId());
System.out.println(container.getKieBase());
}
public static KieContainer build(KieServices kieServices){
KieFileSystem fileSystem=kieServices.newKieFileSystem();
ReleaseId releaseId=kieServices.newReleaseId("com.example.rulesengine",
"model-test", "1.0-SNAPSHOT");
fileSystem.generateAndWritePomXML(releaseId);
//fileSystem.write("D:/workspace/DroolSamples/src/main/resources/rules/rules.drl", getResource(kieServices, "D:/workspace/DroolSamples/src/main/resources/rules/rules.drl"));
addRule(fileSystem);
KieBuilder kieBuilder = kieServices.newKieBuilder(fileSystem);
kieBuilder.buildAll();
if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
throw new RuntimeException("Build Errors:\n" +
kieBuilder.getResults().toString());
}
return kieServices.newKieContainer(releaseId);
}
#SuppressWarnings("restriction")
private static void addRule(KieFileSystem kieFileSystem) {
PackageDescrBuilder packageDescrBuilder = DescrFactory.newPackage();
packageDescrBuilder
.name("com.sample.model")
.newRule()
.name("Is of valid age")
.lhs()
.pattern("Person").constraint("age < 18")
.id("$a", true).end()
//.pattern().id("$a", false).end()
.end()
.rhs("$a.setShowBanner( false );")
//.rhs("insert(new Person())")
.end();
String rules = new DrlDumper().dump(packageDescrBuilder.getDescr());
KieFileSystem fileSystem=kieFileSystem.write("D:/newrule.drl", rules);
try{
// create new file
File file = new File("src/main/resources/rules/test.drl");
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(rules);
// close connection
bw.close();
System.out.println("File Created Successfully");
}catch(Exception e){
System.out.println(e);
}
}
private static Resource getResource(KieServices kieServices, String resourcePath) {
try {
// InputStream is = com.google.common.io.Resources.getResource(resourcePath).openStream(); //guava
InputStream is=new FileInputStream(new File(resourcePath));
return kieServices.getResources()
.newInputStreamResource(is)
.setResourceType(ResourceType.DRL);
} catch (IOException e) {
throw new RuntimeException("Failed to load drools resource file.", e);
}
}
}

Set FopFactoryBuilder baseURI to jar classpath

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.

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

Getting started with Stanford CoreNLP

I'm working in Java with the NetBeans IDE. I've downloaded the Stanford CoreNLP from their website and have no idea how to 'get it to work' in my Java project. I would like to be able to get this demo code working:
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.process.DocumentPreprocessor;
import edu.stanford.nlp.process.PTBTokenizer;
public class TokenizerDemo {
public static void main(String[] args) throws IOException {
for (String arg : args) {
// option #1: By sentence.
DocumentPreprocessor dp = new DocumentPreprocessor(arg);
for (List sentence : dp) {
System.out.println(sentence);
}
// option #2: By token
PTBTokenizer ptbt = new PTBTokenizer(new FileReader(arg),
new CoreLabelTokenFactory(), "");
for (CoreLabel label; ptbt.hasNext(); ) {
label = ptbt.next();
System.out.println(label);
}
}
}
}
But I have no idea how to achieve this. Off the bat, my import statements produce errors (can't find ___ package) Can someone provide step by step instructions for how to get this code to work?
When you downloaded Stanford CoreNLP it came with a file stanford-corenlp-<VERSION>.jar and a stanford-corenlp-<VERSION>-models.jar that you should put on the classpath.
This answer tells you how to do that with NetBeans: How to setup classpath in Netbeans?

ClientWithResponseHandler example Gives an ERROR?

I've tried hard to solve this and I couldn't. I'm trying to use httpClient 4.1.2 from apache. As logic I started with the example, the problem is that I'm having some strange error that I don't understand. This is the deal:
package ClientWithResponseHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class Main {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = **httpclient.execute(httpget, responseHandler);**
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
The error is with "httpclient.execute(httpget, responseHandler);" IT says that it cannot find the method execute(HttpGet,ResponseHandler)
The question shouldn't the example work? What am I doing wrong?! :S
I got the same error too. I resolved it by adding the "httpcore-4.2.1.jar". Then it started complaining about the Class Def not found for logging. So I added "commons-logging-1.1.1.jar" and now I think it works fine. Both these files can be found along with "httpclient-4.2.1.jar".
Hope this helps.