Hot questions for Using JasperReports in jasperserver

Question:

I'm trying to retrieve resource from Jasperserver repository using its java API, according to jasper report server ultimate guide, I should get an instance of the ExecutionContext interface:

ExecutionContext context = JasperServerUtil.getExecutionContext();

then, get an instance of the RepositoryService interface:

RepositoryService repositoryService = ...; //how??

Now I can get the file using the following code:

FileResourceData fileResourceData = repositoryService.getContentResourceData(context, "/examples/report.pdf");

my question is how can I get the RepositoryService instance?


Answer:

ApplicationContext ctx = StaticApplicationContext.getApplicationContext();
String repositoryServiceName = "repositoryService";
RepositoryService repositoryService = (RepositoryService) ctx.getBean(repositoryServiceName);
ExecutionContext context = JasperServerUtil.getExecutionContext();
Resource resource = repositoryService.getResource(context, fileURI);

Question:

I am attempting to update Jasper Reports Server, and having an issue with Java. It uses Tomcat to run java. I did not install java on this server, and I am not very familiar with java. Java was installed in a folder called /opt/jasperreports-server-cp-5.0.0/apache-tomcat/java/bin/. I do not believe Java was installed correctly, and it is telling me that the JAVA_HOME is not defined correctly.

We cannot execute /opt/jasperreports-server-cp-5.0.0/apache-tomcat/java/bin/java

Java is located in that directory.

I ran the following in a bash shell:

export JAVA_HOME="/opt/jasperreports-server-cp-5.0.0/apache-tomcat/java"
export PATH=$JAVA_HOME/bin:$PATH

Can you please help me on what I am doing wrong when setting the JAVA_HOME, or does it have something to do with the java folder? should I reinstall Java altogether?


Answer:

You say the file /opt/jasperreports-server-cp-5.0.0/apache-tomcat/java/bin/java exists, right ?

Can you execute it ? Can it execute standard jar file ?

Question:

Locally I have a master.jrxml report and some subreport.jrxml and can load and manipulate the subreport via ReportDesign design = JRXmlLoader.load( "/local-file-dir/path/to/subreport.jrxml" ) in the Scriptlet code.

On the server, the above load method (trigged by my master.jrxml) obviously cannot deal with repo paths, no matter what I tried (basically net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: ...)

(subreport.jrxml uploaded as a JRXML File Resource - not as Report with invisibly created folder structures ; subreport-attached.jrxml uploaded as a file resource of my master.jrxml Report )

  • apwop) absolute repo path without protocol prefix, e.g. /repo/path/subreport.jrxml
  • apwp) absolute repo path with protocol prefix, e.g. repo:/repo/path/subreport.jrxml
  • rpwop) relative repo path without protocol prefix, e.g. subreport-attached.jrxml
  • rpwp) relative repo path with protocol prefix, e.g. repo:subreport-attached.jrxml

I also tried the following with the above uri variants as found elsewhere in the web without success:

  • JRXmlLoader:

    JRXmlLoader.load(
      new DefaultRepositoryService( 
        DefaultJasperReportsContext.getInstance() 
      ).getInputStream( subrepPath )
    
  • RepositoryUtil:

    RepositoryUtil.getInstance( 
      DefaultJasperReportsContext.getInstance() 
    ).getInputStreamFromLocation( subrepPath )
    
  • JasperServerUtil: similar to this I am still trying out and will report back (had problems with proper Maven jasperserver libraries support till now - other problem I may address in another question)
    • update: it worked: see my answer below

Answer:

Woohoo! :) The last approach with the com.jaspersoft.jasperserver.api.metadata.common.service.RepositoryService worked like this:

JasperDesign design = JRXmlLoader.load(
   ( (RepositoryService) StaticApplicationContext.getApplicationContext()
     .getBean( "repositoryService" ) 
   )
   .getResourceData( JasperServerUtil.getExecutionContext() , 
     "repo:/some/where/subreport.jrxml" )
   .getDataStream()

Puh! hard birth.

Question:

I need to implement a BI and reporting module for a custom ERP system. ERP is built using Java/JSP, Spring3, Struts2, Hibernate3, & MySQL; while security stuff is managed by spring security.

As off my current findings, one of the standard approach to use jasperserver for my purpose would be:

  • To setup jasperserver as simple installed application on my server
  • Create & Manage the BI related stuff, dashboards and reporting there
  • and use web-service/iFrame/SSO approach to embed the required reports and dashboard into my ERP screen(s).

My question is that, what if I get source code of jasperserver and add it to my ERP's workspace in Eclipse, as just another java project and then try to use custom data source for under lying jasperserver; in order to power the reports from with-in my web-application? Of course the reports & dashboard still needs to be designed in iReport or JasperDesigner, but for filling the data i'll use my own code.

Can this also solve the issue of managing 2 separate apps? Does JasperServer source code helps here? Is this feasible? or is this even some thing practically achievable in a given time period?

Please suggest. Thanks


Answer:

Jasper Reports can also be used as a library and it works like any other Java library, by the way, you can get the library from here: https://community.jaspersoft.com/project/jasperreports-library (note that it's also included on Jasper Server and iReports)

Question:

I have created my own Java Class (type) to have life just a little easier when displaying money (euro)-values in jasper reports.

    public class Euro extends Number implements Comparable<Euro> {

    @Override
    public String toString() {...}

    @Override
    public boolean equals(Object obj) {...}

   @Override
   public int hashCode() {...}

}

The data is displayed in table and everything works fine. Even sorting the whole column works great. But, if i want to filter the column like "is greater than" - no data is displayed after filtering.

When i changed the type of the data to BigDecimal sorting works.

What i'm doing wrong? Or can anyone tell me what exaclty jasper do when it tries to filter data?


Answer:

The problem was hat jasper doesn't know the correct data-type of the column, which should be filtered.

So, you have to define which field or variable should be filtered:

The columns in the table that are neither sortable nor filterable contain complex formulas in their detail text field expressions. JIVE looks at the expression in the detail text field to understand what is the data source field or variable it needs to sort and filter after. When the text field uses a simple expression with only the name of a field or variable, things work smooth.

Another approach is to [...] specify at column level in the table component, which is the field or variable to use for sorting and filtering, using one of the following two custom properties that can be set in the column tag/object:

net.sf.jasperreports.components.table.column.field
net.sf.jasperreports.components.table.column.variable

How to make JIVE filtering/soring feature work on column in the table that contains expression

Question:

I'm working to make client rest service with jasperserver to generate reports. I'm using the following code to make that:

I have problem in setting server url and report path, for server url I put http://localhost:8081/jasperserver/ and as shown in next image I put report path rest/report/mytest/my_report but I get 404 not found error in line

File remoteFile = resource.get(File.class);

So how can I get the proper report path from jasperserver?

public class App2 {

private final static String serverUrl = "http://localhost:8081
   /jasperserver/";
private final static String serverUser = "jasperadmin";
private final static String serverPassword = "jasperadmin";

public static void main(String arg[]) throws Exception {
    Report reporte = new Report();
    reporte.setFormat("pdf");
    reporte.setOutputFolder("/home/ali/images");
    ClientConfig clientConfig;
    Map<String, String> resourceCache=new HashMap<String, String>();
    clientConfig = new DefaultApacheHttpClientConfig();
    clientConfig.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
    clientConfig.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
    ApacheHttpClient client = ApacheHttpClient.create(clientConfig);
    client.addFilter(new HTTPBasicAuthFilter(serverUser, serverPassword));
    String describeResourcePath = "/rest/resource" + "/mytest/my_report/";
    String generateReportPath = "/rest/report" + "/mytest/my_report/" + "?RUN_OUTPUT_FORMAT=" + reporte.getFormat();
    WebResource resource = null;
    String resourceResponse = null;
    if (resourceCache.containsKey(describeResourcePath)) {
        resourceResponse = resourceCache.get(describeResourcePath);
    } else {
        resource = client.resource(serverUrl);
        resource.accept(MediaType.APPLICATION_XML);
        resourceResponse = resource.path(describeResourcePath).get(String.class);
        resourceCache.put(describeResourcePath, resourceResponse);
    }
    Document resourceXML = parseResource(resourceResponse);
    resourceXML = addParametersToResource(resourceXML, reporte);
    resource = client.resource(serverUrl  + generateReportPath);
    resource.accept(MediaType.TEXT_XML);
    System.out.println(resource);
    String reportResponse = resource.put(String.class, serializetoXML(resourceXML));
    String urlReport = parseReport(reportResponse);
    resource = client.resource(urlReport);
    System.out.println(resource);
    File destFile = null;
    try {
        File remoteFile = resource.get(File.class);
        File parentDir = new File(reporte.getOutputFolder());
        destFile = File.createTempFile("report_", "." + getExtension(reporte.getFormat()), parentDir);
        FileUtils.copyFile(remoteFile, destFile);
    } catch (IOException e) {
        throw e;
    }
}

/**
 * 
 * @return
 * @throws DocumentException
 */
private static Document parseResource(String resourceAsText) throws Exception {
    // LOGGER.debug("parseResource:\n" + resourceAsText);
    Document document;
    try {
        document = DocumentHelper.parseText(resourceAsText);
    } catch (DocumentException e) {
        throw e;
    }
    return document;
}

/**
 * 
 */
private static String parseReport(String reportResponse) throws Exception {
    String urlReport = null;
    try {
        Document document = DocumentHelper.parseText(reportResponse);
        Node node = document.selectSingleNode("/report/uuid");
        String uuid = node.getText();
        node = document.selectSingleNode("/report/totalPages");
        Integer totalPages = Integer.parseInt(node.getText());
        if (totalPages == 0) {
            throw new Exception("Error generando reporte");
        }
        urlReport = serverUrl + "/report/" + uuid + "?file=report";
    } catch (DocumentException e) {
        throw e;
    }
    return urlReport;
}

/**
 * 
 * @param resource
 * @param reporte
 * @return
 */
private static Document addParametersToResource(Document resource, Report reporte) {
    // LOGGER.debug("addParametersToResource");

    Element root = resource.getRootElement();
    Map<String, String> params = reporte.getParams();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (key != null && value != null) {
            root.addElement("parameter").addAttribute("name", key).addText(value);
        }
    }
    // LOGGER.debug("resource:" + resource.asXML());
    return resource;
}

/**
 * 
 * @param aEncodingScheme
 * @throws IOException
 * @throws Exception
 */
private static String serializetoXML(Document resource) throws Exception {
    OutputFormat outformat = OutputFormat.createCompactFormat();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    outformat.setEncoding("ISO-8859-1");

    try {
        XMLWriter writer = new XMLWriter(out, outformat);
        writer.write(resource);
        writer.flush();
    } catch (IOException e) {
        throw e;
    }
    return out.toString();
}

/**
 * 
 * @param format
 * @return
 */
private static String getExtension(String format) {
    String ext = null;
    if (format.equals(Report.FORMAT_PDF)) {
        ext = "pdf";
    } else if (format.equals(Report.FORMAT_EXCEL)) {
        ext = "xls";
    }
    return ext;
}

}

Answer:

I have fixed it,I need to change path

urlReport = serverUrl + "/report/" + uuid + "?file=report"; 

to

urlReport = serverUrl + "/rest/report/" + uuid + "?file=report";

in parseReport method

private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
    Document document = DocumentHelper.parseText(reportResponse);
    Node node = document.selectSingleNode("/report/uuid");
    String uuid = node.getText();
    node = document.selectSingleNode("/report/totalPages");
    Integer totalPages = Integer.parseInt(node.getText());
    if (totalPages == 0) {
        throw new Exception("Error generando reporte");
    }
    urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
    throw e;
}
return urlReport;

}

Question:

I have created jrxml report by iReport. Then I have run it with JasperServer and it work perfectly. I have generate pdf report by this URL:

http://localhost:8081/jasperserver/flow.html/flowFile/my_report.pdf

It works well but when I tried to refresh the page I get this error:

An id is required to lookup a FlowDefinition

Also when I try to call this REST service in JasperServer client application I get this error:

com.sun.jersey.api.client.UniformInterfaceException: Client response status: 500

This is the Java client application to call the REST service:

public final static String serverUrl = "http://localhost:8081/jasperserver/flow.html/flowFile/my_report.xls";
public final static String serverUser = "jasperadmin";
public final static String serverPassword = "jasperadmin";

static File outPutDir= new File(System.getProperty("java.io.tmpdir"));

public static void main(String[] args) {
    try {
        Report report = new Report();
        report.setUrl("/reports/samples/Employees");
        report.setOutputFolder(outPutDir.getAbsolutePath());
        JasperserverRestClient client = JasperserverRestClient.getInstance(serverUrl, serverUser, serverPassword);
        File reportFile  = client.getReportAsFile(report);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Answer:

flowId

When calling flow.html you must provide an action, which is put into the flowId. JasperServer is using the flow.html to provide an interface which can be accessed over the URL. For example if calling a report this would be:

_flowId=viewReportFlow

Also the report and parameters have to be provided. So with this in mind the URL could look like this:

http://localhost:8081/jasperserver/flow.html?_flowId=viewReportFlow&reportUnit=/reports/samples/Employees&j_username=the_user&j_password=secret&output=pdf

Server error

When connecting to the server, this URL is used

http://localhost:8081/jasperserver/flow.html/flowFile/my_report.xls

This is not the server URL used by JasperserverRestClient. The server URL should look like this:

http://localhost:8081/jasperserver

NOTE: flow.html is for accessing JasperServer without logging into the UI. It is not an application path where you should put your reports.

Question:

Following information here: http://community.jaspersoft.com/documentation/jasperreports-server-ultimate-guide/v55/report-data-source-service-api and here: http://community.jaspersoft.com/questions/516771/bean-datasource-pass-parameter Regarding the usage of the class: ReportDataSourceService for fetching the report's parameters. I'm trying to find a JAR file which will contain this class. None of the Jasper JARs I found contained it. I'd appreciate to know where to find it. Thanks


Answer:

This class is in the jasper report server distribution, not in the regular jasper report distribution

jasperreports-server/releases

You will find it inside the war file jasperserver.war\WEB-INF\lib\jasperserver-api-metadata-6.2.0.jar\

Question:

I am a begginer in report generation using jasper report server. I want to show reports deployed in jasper server in my web application. I have read this article : http://community.jaspersoft.com/wiki/embedding-using-http-api

I am doing this for self learning only so there is no issue of security.

So far i have done : I made a web application and in my JSP i am using the following to embedding reports in JSP :

 <c:import url="http://localhost:8080/jasperserver/flow.html?_flowId=viewReportFlow&standAlone=true&_flowId=viewReportFlow&ParentFolderUri=%2Freports%2FGraphD&reportUnit=%2Freports%2FGraphD%2FMainReport1&j_username=jasperadmin&j_password=jasperadmin" />

I have downloaded a theme and uploaded to jasper server and made it active, so as to remove header and jaspersoft logo etc.

Now when I run my application through tomcat, In browser it keeps reloading and nothing appears.

Note : If i dont pass username and password as parameters in request then jasper server login page appears but when i try to login , error is displayed : j_spring_security_check, The requested resource is not available.

I don't understand what i am doing wrong. :'(

Please Help.


Answer:

Try this maybe. <c:import var="data" url="http://localhost:8080/jasperserver/flow.html?_flowId=viewReportFlow&standAlone=true&_flowId=viewReportFlow&ParentFolderUri=%2Freports%2FGraphD&reportUnit=%2Freports%2FGraphD%2FMainReport1&j_username=jasperadmin&j_password=jasperadmin"/> <c:out value="${data}"/>

Question:

i know that this is a trivial question but this is the best place to ask it. I have a database which is hosted on a website. I have written a Java program that accesses the database and through this program the user can view reports. I used Jasper Reports for this. Now i have a website where the user can log in and would like the user to be able to view the exact same reports but through my website. In other words, what is the equivalent of Jasper Reports for a web page? I know that there is something called JasperReports Server but Im not sure if that is what i am looking for and how is it possible to incorporate into into my html/php site. Can someone please direct me to the right place? Thanks.


Answer:

You can display Jasper reports using any of the following approaches:

  • Publish JRXML reports into Jasper server and embed Jasper server into your application using IFrame.
  • Publish JRXML reports into Jasper server and call those reports in your application using Soap or Restful web services.
  • Use Jasper API to display jasper reports directly in your application. Refer Jasper reports for Java tutorials for more info.

Thanks,

Srikanth Kattam

Question:

I have a .jrxml file which is used to generate a jasper report and then a a pdf file from that. for that I used this code.

JasperCompileManager.compileReportToFile("C:/Users/my-pc/Desktop/letters/report xml/testreport.jrxml");

But I got an issue with xsd and dtd which is described here. That article introduces a way to solve the issue by using a java program called LegacyJasperInputStream.

This is how I should call it.

JasperDesign design = JRXmlLoader.load(
   new LegacyJasperInputStream(new FileInputStream("C:/Users/my-pc/Desktop/letters/report xml/testreport.jrxml"))
);

My question is what is this JasperDesign. Can I compile that into .jasper. If so, how to do it?

Thanks!


Answer:

After searching and trying....Here we go.

net.sf.jasperreports.engine.design.JasperDesign design = JRXmlLoader.load(
                    new LegacyJasperInputStream(new FileInputStream("C:/Users/my-pc/Desktop/letters/report xml/testreport.jrxml"))
                    );
            JasperReport jasperReport = asperCompileManager.compileReport(design);

            JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
            System.out.println("INFO: Report is filled and to be exported to pdf now");

            try {
                // export report to pdf
                JasperExportManager.exportReportToPdfFile(print, "C:/Users/my-pc/Desktop/letters/report xml/test.pdf");
                System.out.println("DEBUG: Expported to pdf");
            } catch (Exception e) {

                System.out.println("EXCEPTION: while generating pdf : "+e);
            }