Hot questions for Using JasperReports in xml

Question:

I am using the following code to print a report:

    JasperPrint jasperPrint = null;

    try {
        JasperCompileManager.compileReportToFile("C:\\Nevro\\reports\\salesDetails.jrxml");
        jasperPrint = JasperFillManager.fillReport("C:\\Nevro\\reports\\salesDetails.jasper", new HashMap(),
                new JRTableModelDataSource(itemTable.getModel()));
        JasperViewer jasperViewer = new JasperViewer(jasperPrint);
        jasperViewer.setVisible(true);
    } catch (JRException ex) {
        Logger.getLogger(Invoice.class.getName()).log(Level.SEVERE, null, ex);
    }

In the location C:\Nevro\reports\ I have created salesDetails.jrxml. Then in Java code I read the file and compile it. I expected to create compiled file as salesDetails.jasper but it create only null.jasper.

Can any one give me a reason and solution to sort this out?


Answer:

The filename is generated by this line of code within the Jasper library:

File destFile = new File(sourceFile.getParent(), jasperDesign.getName() + ".jasper");

It takes the path of the jrxml file and generates the output file based on the name of your report (configured in the XML). In your case the report has no name, so you get null.jasper.

Question:

I'm trying to pass to template of a jasper reports string location. So I'm passing key of a parameter inside template and value. Everything was working when I had image inside my project, but I would like to have it on the other place. Is there any way to read parameters from, for instance properties file? I don't know why this sollution is not working:

My image:

<parameter name="imagesDir" class="java.lang.String" isForPrompting="false"/>

...

<image isLazy="true">
    <reportElement key="image-1" style="PHLabel" x="0" y="0" width="160" height="33"/>
    <imageExpression class="java.lang.String"><![CDATA["$P{imagesDir}"+"logo.bmp"]]></imageExpression>
</image>

error:

Error during exporting report statement_account_10 to PDF.
net.sf.jasperreports.engine.JRException: Byte data not found at : 
((java.lang.String)parameter_imagesDir.getValue())logo.bmp

Answer:

Ok i found it... Should be:

<image isLazy="true">
    <reportElement key="image-1" style="PHLabel" x="0" y="0" width="160" height="33"/>
    <imageExpression class="java.lang.String"><![CDATA[$P{imagesDir}+"logo.bmp"]]></imageExpression>
</image>

Question:

I'm working with Spring MVC 4.3.4 and Jasperreports 6.3.1 in a RESTful web project (Maven project in Netbeans). When I get an arraylist of objects in the controller, this error appears:

Grave:   Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.ObjectWriter.forType(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/ObjectWriter;
org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.ObjectWriter.forType(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/ObjectWriter;
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:978)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)

Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.ObjectWriter.forType(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/ObjectWriter;
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:265)
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:232)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
... 43 more

I reviewed the dependencies of JasperReports 6.3.1 and I saw that the used version of the Jackson library is 2.1.4 (a bit old), and even in version 6.4.0 they also use that version.

My question is How do I solve this problem? Because in my pom.xml I tested including the latest version of Jackson (2.8.5) and still it seems that the project will not take it.

My pom.xml dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports</artifactId>
        <version>6.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.jsondoc</groupId>
        <artifactId>jsondoc-core</artifactId>
        <version>1.2.16</version>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

A little example of a get resource in my controller with json-doc annotations:

//------------ LISTAR ----------------
@ApiMethod(
    path = "/answers",
    description = "Lista las respuestas registradas.",
    verb = ApiVerb.GET,
    produces =
    {
        MediaType.APPLICATION_JSON_VALUE
    },
    visibility = ApiVisibility.PUBLIC,
    stage = ApiStage.ALPHA
)
@ApiErrors(
    apierrors =
    {
        @ApiError(code = "500", description = "Error del servidor al procesar la solicitud."),
    }
)
@ApiResponseObject(clazz = Answer.class)
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Answer>> list() throws Exception
{
    List<Answer> list = answerService.list();

    if (list.isEmpty())
    {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    return new ResponseEntity<>(list, HttpStatus.OK);
}

Thanks a lot for your help!


Answer:

Never is too late, but I had the same problem with Spring MVC 4.3.5 on Wildfly-8.2.1. My solution are like @Tiago Coelho mentioned. Replace in \WildFly-8.2.1.Final\modules\system\layers\base\com\fasterxml\jackson\core, inside the three subfolders jackson-annotations, jackson-core and jackson-databind, the jar file for the lastest from jackson-core in maven repository, and then modify the file call module.xml replacing the version of the old jar for the new one. This work for me, Cheers.

Question:

I trying to load jasper report (.jrxml) that i created, i named the report "JREmp1.xml". but i got this error

"HTTP Status 500 - Request processing failed; nested exception is net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: D:\printpdf.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JasperExample\jasper\JREmp1.jrxml (The system cannot find the path specified)"

how to got the exact location? here is my JREmp1.xml file location :

and here is code in my controller class :

@RequestMapping(value = "/generateReport", method = RequestMethod.POST)
public String generateReport(
        @Valid @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
        BindingResult result, Model model, HttpServletRequest request,
        HttpServletResponse response) throws JRException, IOException,
        NamingException {

    if (result.hasErrors()) {
        System.out.println("validation error occured in jasper input form");
        return "loadJasper";

    }

    String reportFileName = "JREmp1";
    JasperReportDAO jrdao = new JasperReportDAO();

    Connection conn = null;

    try {
        conn = jrdao.getConnection();

        String rptFormat = jasperInputForm.getRptFmt();
        String noy = jasperInputForm.getNoofYears();

        System.out.println("rpt format " + rptFormat);
        System.out.println("no of years " + noy);

        HashMap<String, Object> hmParams = new HashMap<String, Object>();

        hmParams.put("noy", new Integer(noy));

        hmParams.put("Title", "Employees working more than " + noy
                + " Years");

        JasperReport jasperReport = jrdao.getCompiledFile(reportFileName,
                request);

        if (rptFormat.equalsIgnoreCase("html")) {
            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, hmParams, conn);
            jrdao.generateReportHtml(jasperPrint, request, response); // For
            // HTML
            // report
        }
        else if (rptFormat.equalsIgnoreCase("pdf")) {
            jrdao.generateReportPDF(response, hmParams, jasperReport, conn); // For
            // PDF
            // report
        }
    } catch (SQLException sqlExp) {
        System.out.println("Exception::" + sqlExp.toString());
    } finally {
        if (conn != null) {
            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return null;
}

Here is the code in my JasperReportDAO class :

public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
    System.out.println("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    // If compiled file is not found, then compile XML template
    if (!reportFile.exists()) {
        JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    }
    JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
    return jasperReport;
}


public void generateReportHtml( JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp) throws IOException, JRException {
    HtmlExporter exporter=new HtmlExporter();
    List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
    jasperPrintList.add(jasperPrint);
    exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
    exporter.setExporterOutput( new SimpleHtmlExporterOutput(resp.getWriter()));
    SimpleHtmlReportConfiguration configuration =new SimpleHtmlReportConfiguration();
    exporter.setConfiguration(configuration);
    exporter.exportReport();

}


public void generateReportPDF (HttpServletResponse resp, Map parameters, JasperReport jasperReport, Connection conn)throws JRException, NamingException, SQLException, IOException {
    byte[] bytes = null;
    bytes = JasperRunManager.runReportToPdf(jasperReport,parameters,conn);
    resp.reset();
    resp.resetBuffer();
    resp.setContentType("application/pdf");
    resp.setContentLength(bytes.length);
    ServletOutputStream ouputStream = resp.getOutputStream();
    ouputStream.write(bytes, 0, bytes.length);
    ouputStream.flush();
    ouputStream.close();
}

and here is my JasperInputForm class :

public class JasperInputForm {

    @NotEmpty
    private String noofYears;
    private String rptFmt="Html";

    public String getRptFmt() {
        return rptFmt;
    }

    public void setRptFmt(String rptFmt) {
        this.rptFmt = rptFmt;
    }

    public String getNoofYears() {
        return noofYears;
    }

    public void setNoofYears(String noofYears) {
        this.noofYears = noofYears;
    }

}

how to get my JREmp1.jrxml file location properly? I develop this report for Spring MVC application

UPDATE : Here is my complete function code after i update with @Wilson answer (i go with second option that @Wilson said) : this function is inside JasperReportDAO :

public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException, MalformedURLException, URISyntaxException {
    System.out.println("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    //File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    URL resourceUrl = request.getSession().getServletContext().getResource("/WEB-INF/jasper/" + fileName + ".jrxml");
    File reportFile = new File(resourceUrl.toURI());

    // If compiled file is not found, then compile XML template
    if (!reportFile.exists()) {
               JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
        }
        JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
       return jasperReport;
}

and i got this error

"HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: URI scheme is not "file""

How to solve this?


Answer:

There is a number of way to do to read file with ServeltContext:

1. Use ServletContext#getRealPath

String fullPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper/" + fileName + ".jrxml");

This will get you the full system path to the resource you are looking for. However, it will not work if the container do not expand the WAR file.

2. Use ServletContext#getResource

URL resourceUrl = request.getSession().getServletContext().getResource("/WEB-INF/jasper/" + fileName + ".jrxml");
File file = new File(resourceUrl.toURI());

This will return the URL no matter what container you use and where the application is installed.

3. User ServletContext#getResourceAsStream

InputStream resourceStream = request.getSession().getServletContext().getResourceAsStream("/WEB-INF/jasper/" + fileName + ".jrxml");

This is an alternative of ServletContext#getResource to get an inputSteam

UPDATE:

The URL return from ServletContext#getResource may not be a file URL and it may cause issue. Please try ServletContext#getResourceAsStream with JasperCompileManager#compileReportToFile:

JasperDesign jasperDesign = JRXmlLoader.load(resourceStream);
JasperCompileManager.compileReportToFile(jasperDesign, jasperFilePath);

I found that your are trying to write jasper report file into your program distribution which should be avoid. The preferred way is to pre-compile your report and put into your WAR file or put the compiled jasper report into a temporary directory.

Following is full code example:

public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException, IOException {
    // Create temporary folder to store jasper report as you should not write a resource into your program
    // distribution
    String tempFolderPath = System.getProperty("java.io.tmpdir") + File.separator + "jasperReport";
    File tempFolder = new File(tempFolderPath);
    if (!tempFolder.exists()) {
        tempFolder.mkdirs();
    }
    String jasperFilePath = tempFolderPath + File.separator + fileName + ".jasper";
    File reportFile = new File(jasperFilePath);
    // If compiled file is not found, then compile XML template
    if (!reportFile.exists()) {
        InputStream jRXmlStream = request.getSession().getServletContext().getResourceAsStream
                ("/WEB-INF/jasper/" + fileName + ".jrxml");
        JasperDesign jasperDesign = JRXmlLoader.load(jRXmlStream);
        JasperCompileManager.compileReportToFile(jasperDesign, jasperFilePath);
    }
    JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
    return jasperReport;
}

Question:

I am trying to iterate the values of the HashMap passed as parameters to jrxml, in the HashMap the values are passed as List.

Example

List<String> severity = // some values;
List<String> messages = // some values;

LinkedHashMap parameters = new LinkedHashMap();
parameters.put("severity", severity);
parameters.put("messages", messages);

jPrint = JasperFillManager.fillReport(jasperreport,parameters,new JREmptyDataSource());     
JasperExportManager.exportReportToPdfStream(jPrint,baos);  

How can I iterate these List inside jasper report the jrxml?


Answer:

You can create a new datasource with jasper report using

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{severity})

This datasource can be used for subreport as dataSourceExpression:

<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{severity})]]></dataSourceExpression>

or when using subDataset in jr:table, jr:list components

<datasetRun subDataset="listDs" uuid="99b1de41-5185-4b8f-9cfe-011e7b4cf22d">
   <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{severity})]]></dataSourceExpression>
</datasetRun>

Be aware since your Bean is a java primitive type (String) to access it directly you need to use this field description

<field name="_THIS" class="java.lang.String"/>

See this for more information: Passing the List of primitive type objects as datasource for subreport

Question:

I tried answer from this site to merge two jrxml jasper into 1 pdf file. Created file contain two page...

How to merge two jrxml into one page?

JasperPrint jasperPrint1 = JasperFillManager.fillReport(getClass().getResourceAsStream("/coba.jasper"), param, new JREmptyDataSource());
JasperPrint jasperPrint2 = JasperFillManager.fillReport(getClass().getResourceAsStream("/coba2.jasper"), param2, new JREmptyDataSource());

            List pages = jasperPrint2.getPages();
            for (int i = 0; i < pages.size(); i++) {
                JRPrintPage object = (JRPrintPage)pages.get(i);
                jasperPrint1.addPage(object);
            }                                   
JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, jasper);
            OutputStream output = new FileOutputStream(new File("d:\\demo.pdf"));
            exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, output);
            exporter.exportReport();

Answer:

This is since you are adding a page addPage, you need to add the elements on a page to another page.

JRPrintPage page1 = jasperPrint1.getPages().get(0);
List<JRPrintPage> pages2 = jasperPrint2.getPages();
for (JRPrintPage page : pages2) {
   List<JRPrintElement> elements = page.getElements();
   for (JRPrintElement element : elements) {
     page1.addElement(element);
   }
}

This code will add all elements of jasperPrint2 (in all its pages) in page 1 on jasperPrint1

NOTE: Error handling (Nullpointer, ArrayIndexOutOfBounds) is beyond the scope of the example.

Question:

We recently integrated jasper report to our system. Now we can run report and show result to users with jasper report via standard way, run and show result to user.

But in some cases we need to save result to an object storage and show user when requested, as a document. As far as I know JasperPrint is a serialized object. saving report result to object storage as a serialized object is not a good way as we experienced our prior report tool. if the object changed the serialization mechanism could not deserialize object.

So we want to save jasper result in xml format to object storage but we couldn't find any way to show exported xml in JRViewer.

Is there any way to convert exported xml to a visual form?


Answer:

Jasper Report provides two method's for saving and loading your filled report, JasperPrint (note: excluding export's to other formats as pdf,xls ecc, since it would be very difficult to load and export to another format).

With courtesy of @Robert Mugattarov, What is the difference between JasperReport formats?

.jrprint is a serialized JasperPrint object i.e. an actual report instance i.e. a template that has been filled with data. This file can be deserialized back into a JasperPrint object.

.jrpxml is a human readable XML represenatation of a JasperPrint object i.e. an XML version of a template that has been filled with data. This file can be unmarshalled back into a JasperPrint object.

Since you do not wish do have a serialized object, the solution that remains is the jrpxml format in xml.

Example of saving and loading to jrpxml.

//Save JasperPrint to jrpxml (xml format)
JRXmlExporter exporter = new JRXmlExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(new File("myJasperPrint.jrpxml")));
exporter.exportReport();

//Load jrpxml to JasperPrint object
JasperPrint print = JRPrintXmlLoader.load("myJasperPrint.jrpxml");

//To show it in JasperViewer
JRViewer jrv = new JRViewer(print);

If you need to reduce file size I suggest that you zip/unzip the jrpxml file.

What is a good Java library to zip/unzip files?

Question:

I'd need to debug Jasper Reports to be able to know why my report appears empty, well, it just displays static information, plus parameters passed by, but I have a sub-report that should be listing some information and this part is empty.

Following some examples in the web I have used the following log4j2.xml configuration file, but:

  1. I get no log file create, well, the file is created but it remains empty.
  2. How to configure to get output debug from Jasper Reports? If the sub-report gets empty, I guess it must be failing somewhere so I need to discover what's going on.

Here's my log4j2.xml config file:

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
    <Properties>
        <Property name="basePath">E:\\logs</Property>
    </Properties>

    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/urnavirtual.log" filePattern="${basePath}/urnavirtual-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout   pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="net.sf.jasperreports" level="ALL" additivity="false">
            <appender-ref ref="fileLogger" level="ALL" />
        </Logger>
        <Root level="ALL" additivity="false">
            <appender-ref ref="console" />
        </Root>
    </Loggers>
</Configuration>

In my Last test I added logger with "net.sf.jasperreports", but I guess something is not well configured.

  1. Is there any property that should be set to let Jasper Reports know that it must Log their internal errors?
  2. What changes should I use in my log4j2.xml file to successfully log Jasper Report errors

I'm using Eclipse Neon with Java 8.

This is my first question so, I apologize if I'm not clear or I'm against any of the StackOverFlow rules.

Thanks a lot,

Edited: I already have log4j, but even with level=DEBUG, I get no debug output in logs.


Answer:

since jasper reports is using log4j, you need to use a bridge for log4j 2 to work properly. try to add log4j-1.2-api.jar: apache page for the bridge

maven details if you use it: maven repository

Question:

I want to pass a parameter from jsp to jrxml that is used inside a query in subdataset, but when I try I always get empty pdf.

If I try the sql without parameter I have no problem. So I'm guessing that something is wrong in how I pass the parameter.

show.jsp

<%
    Connection conn = null;
    //int id = Integer.parseInt(request.getParameter("ID"));
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","passwd1234");

        File reportFile = new File(application.getRealPath("//T0113.jasper"));
        System.out.println(reportFile);
        Map parameters = new HashMap();
        String sqlCondition = "A11";
        parameters.put("id",sqlCondition);
        byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(),parameters,conn);
        System.out.println(parameters);
        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(bytes,0,bytes.length);
        outStream.flush();
        outStream.close();  
    } catch (Exception ex) {
        out.println("Error : " + ex.getMessage());
    }


%>

my jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.2.0.final using JasperReports Library version 6.2.0  -->
<!-- 2016-01-14T16:09:41 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="T0113" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="84489b82-cfa1-489a-a5e2-404ca58708d2">
    <property name="com.jaspersoft.studio.data.sql.tables" value=""/>
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="TEST0114"/>
    <style name="Table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <subDataset name="T0113" uuid="e911ce63-0ce5-4bb2-b3c8-e6b41cba5852">
        <property name="com.jaspersoft.studio.data.sql.tables" value=""/>
        <property name="com.jaspersoft.studio.data.defaultdataadapter" value="TEST0114"/>
        <parameter name="id" class="java.lang.String"/>
        <queryString>
            <![CDATA[select * from person where '$P{id}']]>
        </queryString>
        <field name="ID" class="java.lang.String">
            <fieldDescription><![CDATA[]]></fieldDescription>
        </field>
        <field name="NAME" class="java.lang.Integer">
            <fieldDescription><![CDATA[]]></fieldDescription>
        </field>
        <group name="ID">
            <groupExpression><![CDATA[$F{ID}]]></groupExpression>
        </group>
        <group name="NAME">
            <groupExpression><![CDATA[$F{NAME}]]></groupExpression>
        </group>
    </subDataset>
    <queryString>
        <![CDATA[select * from person]]>
    </queryString>
    <field name="ID" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="NAME" class="java.lang.Integer">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <group name="ID">
        <groupExpression><![CDATA[$F{ID}]]></groupExpression>
    </group>
    <group name="NAME">
        <groupExpression><![CDATA[$F{NAME}]]></groupExpression>
    </group>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch"/>
    </title>
    <pageHeader>
        <band height="215" splitType="Stretch">
            <componentElement>
                <reportElement x="170" y="15" width="200" height="200" uuid="02e57f61-e30e-429f-a8c6-487a18e7ed07">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                </reportElement>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="T0113" uuid="dd2d7275-311a-4bd0-b7d8-d9948ddc3c1c">
                        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    </datasetRun>
                    <jr:column width="100" uuid="a3a9e148-5c8d-44c9-a76d-38a1b86daf01">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="100" height="30" uuid="8eba1ee4-42c7-4908-a97b-88b6a53faa1e"/>
                                <text><![CDATA[ID]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="100" height="30" uuid="5ee52917-3b1b-4ba3-aed8-581662fb8cd9"/>
                                <textFieldExpression><![CDATA[$F{ID}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="100" uuid="7a689d13-3e08-4683-a53b-768c15825885">
                        <jr:columnHeader style="Table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="100" height="30" uuid="d821fdb7-948a-4f67-90d8-3bf9f0f6da70"/>
                                <text><![CDATA[NAME]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="100" height="30" uuid="0f29f475-aff1-4bad-855a-145e393717cd"/>
                                <textFieldExpression><![CDATA[$F{NAME}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </pageHeader>
    <detail>
        <band height="125" splitType="Stretch"/>
    </detail>
    <summary>
        <band height="42" splitType="Stretch"/>
    </summary>
</jasperReport>

error message

parameter index out of range (1 number of parameters which is 0)

Answer:

You are passing the parameter correctly from jsp to jrxml, this is not your problem.

The problem is that you are not passing the parameter from main report to your subDataset, actually the parameter does not exists in main report.

Solution:

  1. Define the parameter also in the main report, with same name.

    <parameter name="id" class="java.lang.String"/>
    

    This definition will be under your subDataset

  2. Pass the main report parameter in your datasetRun expression to your subDataset

    <datasetRun subDataset="T0113" uuid="dd2d7275-311a-4bd0-b7d8-d9948ddc3c1c">
        <datasetParameter name="id">
            <datasetParameterExpression><![CDATA[$P{id}]]></datasetParameterExpression>
        </datasetParameter>
        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
    </datasetRun>
    

To understand this you need to think of subDataset as a subreport, as another report. The parameter in you main report are not automatically present in the subDataset they need to be defined and their values need to be passed.

If you wan't to pass all parameter in once you can also pass the whole parameter map to your subdataset using this expression. (note, you still need to define them in both main report and subdataset)

<datasetRun subDataset="T0113" uuid="dd2d7275-311a-4bd0-b7d8-d9948ddc3c1c">
        <parametersMapExpression><![CDATA[new java.util.HashMap($P{REPORT_PARAMETERS_MAP})]]></parametersMapExpression>
        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
</datasetRun>

Some comments outside of the questions scope

  1. Its seems that you have a typo on this query select * from person where '$P{id}', it probably should be something like select * from person where theCorrectColumnNameThatIsAVarChar = $P{id}
  2. I see that detail band is empty, there is no need to execute the query select * from person in main report, if you like to display report with empty datasource just use the attribute whenNoDataType="AllSectionsNoDetail" on the jasperReport tag

Question:

I use the following Java code to create an .xml file

public static void main(String[] args) {
        try {

            ArrayList<MyBean> ll = new ArrayList<>();
            ll.add(new MyBean(1));
            ll.add(new MyBean(2));

            FileOutputStream fos = new FileOutputStream("C:\\temp\\mybean.xml");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            XMLEncoder xmlEncoder = new XMLEncoder(bos);
            xmlEncoder.writeObject(ll);
            xmlEncoder.close();

        } catch (Exception e) {
        }
        ;

    }
  public static class MyBean implements Serializable {
        private static final long serialVersionUID = 1L;
        private double fxEffectRealized;
        private double changeWPRealized;

        public MyBean() {

        }
        public MyBean(int i) {
            fxEffectRealized = Math.random() * 100;
            changeWPRealized = Math.random() * 100;
        }

        public double getFxEffectRealized() {
            return fxEffectRealized;
        }

        public void setFxEffectRealized(double fxEffectRealized) {
            this.fxEffectRealized = fxEffectRealized;
        }

        public double getChangeWPRealized() {
            return changeWPRealized;
        }

        public void setChangeWPRealized(double changeWPRealized) {
            this.changeWPRealized = changeWPRealized;
        }


    }

It creates an .xml file which looks like

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_02" class="java.beans.XMLDecoder">
 <object class="java.util.ArrayList">
  <void method="add">
   <object class="com.ch.reports.ReportJasper$MyBean">
    <void property="changeWPRealized">
     <double>12.206382535941362</double>
    </void>
    <void property="fxEffectRealized">
     <double>4.772624038704009</double>
    </void>
   </object>
  </void>
  <void method="add">
   <object class="com.ch.reports.ReportJasper$MyBean">
    <void property="changeWPRealized">
     <double>29.554973174761056</double>
    </void>
    <void property="fxEffectRealized">
     <double>33.64290090087834</double>
    </void>
   </object>
  </void>

 </object>
</java>

But in order for it to be readable by Jasper Reports I really need it to look like

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport>
    <MyBean>
        <changeWPRealized>12.206382535941362</changeWPRealized>
        <fxEffectRealized>4.772624038704009</fxEffectRealized>
    </MyBean>
    <MyBean>
        <changeWPRealized>29.554973174761056</changeWPRealized>
        <fxEffectRealized>33.64290090087834</fxEffectRealized>
    </MyBean>
</jasperReport>

What is the best way of doing this?


Answer:

Using @ChristofferPass's suggestion of JAXB (Thank you!)

public static void main(String[] args) {
        try {
            ListBeans lb = new ListBeans();
            lb.add(new MyBean(1));
            lb.add(new MyBean(2));

            JAXBContext jaxbContext = JAXBContext.newInstance(ListBeans.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(lb, new File("c:\\temp\\mybean.xml"));

        } catch (Exception e) {
        }
        ;

    }

    @XmlRootElement(name = "ROOT")
    public static class ListBeans {

        private List<MyBean> listBeans = null;

        public ListBeans() {

        }
        @XmlElement (name="BEAN")
        public void setListBeans(List<MyBean> listBeans) {
            this.listBeans = listBeans;
        }


        public void add(MyBean mb) {
            if (this.listBeans == null) {
                this.listBeans = new ArrayList<MyBean>();
            }
            this.listBeans.add(mb);
        }


        public static class MyBean {
            private double fxEffectRealized;
            private double changeWPRealized;

            public MyBean() {

            }
            public MyBean(int i) {
              fxEffectRealized = Math.random() * 100;
              changeWPRealized = Math.random() * 100;
            }

            public double getFxEffectRealized() {
              return fxEffectRealized;
            }

            public void setFxEffectRealized(double fxEffectRealized) {
               this.fxEffectRealized = fxEffectRealized;
            }

            public double getChangeWPRealized() {
              return changeWPRealized;
            }

            public void setChangeWPRealized(double changeWPRealized) {
              this.changeWPRealized = changeWPRealized;
            }
        }
     }

Question:

I use in my JRXML some object of my application A like this :

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ResportTest" pageWidth="842" pageHeight="595" orientation="Landscape" whenNoDataType="AllSectionsNoDetail" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.5394743546921226"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<import value="com.test.app.EnumOne"/>
<import value="com.test.app.Test1DTO"/>
<import value="com.test.app.Test1Sub1DTO"/>
<import value="com.test.app.Test1Sub2DTO"/>
<import value="com.test.app.Test2DTO"/>
<import value="com.test.app.EnumTwo"/>

With iReport, i have added my target/classes directory to classpath, everythink is OK.

Now, when i try to compile my JRXML with maven (mvn clean install), i've got an error :

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.949 s
[INFO] Finished at: 2015-04-10T08:17:26+01:00
[INFO] Final Memory: 39M/112M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:jasperreports-maven-plugin:1.0-beta-1:compile-reports (default) on project projectOne: Error co
mpiling report design : C:\ws\projectOne\src\main\resources\jasper\jrxml\ReportTest.jrxml: Error compiling report d
esign : C:\ws\projectOne\src\main\resources\jasper\jrxml\ReportTest.jrxml : Report design not valid :
[ERROR] 1. java.lang.ClassNotFoundException: com.test.app.EnumOne
[ERROR] 2. java.lang.ClassNotFoundException: com.test.app.EnumTwo
[ERROR] 3. java.lang.ClassNotFoundException: com.test.app.Test2DTO

When my build fail, maven had already compile all classe in target/classes. I don't undestand why maven can't find EnumOne, EnumTwo and Test2DTO when it can find the other.

Here my pom.xml for jasper:

              <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jasperreports-maven-plugin</artifactId>
                <version>${version.jasperreports-plugin}</version>
                <configuration>
                    <sourceDirectory>src/main/resources/jasper/jrxml</sourceDirectory>
                    <outputDirectory>src/main/resources/jasper/jasper</outputDirectory>
                    <compiler>net.sf.jasperreports.engine.design.JRJavacCompiler</compiler>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile-reports</goal>
                        </goals>
                        <phase>compile</phase>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>net.sf.jasperreports</groupId>
                        <artifactId>jasperreports</artifactId>
                        <version>${version.jasperreports}</version>
                    </dependency>
                </dependencies>
            </plugin>

Answer:

Ok, i just found the solution. Maven use the dependency jasperreports-maven-plugin with version 1.0-beta-1. I upgraded the dependency to 1.0-beta-2 and it now works !

Question:

The Pre-Requisites

I have recently upgraded from JasperReports version 3.7.6 to 6.4.1. JasperReports-fonts remains at version 5.6.1. I have also made sure to update the core dependencies for each project, and they are now included in the Maven build.

I have a JavaSE-1.8 build path for my server, and this matches my environment too.

The updated Jasper Maven dependencies in the pom.xml are as follows.

<dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports-fonts</artifactId>
        <version>5.6.1</version>
        <type>jar</type>
        <scope>compile</scope>
</dependency>  

<dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports</artifactId>
        <version>6.4.1</version>
        <type>jar</type>
        <scope>compile</scope>
</dependency> 

I realise this is a big version jump and we are bound to encounter some errors, but Maven builds and compiles the .jrxml report files successfully. However, I am getting an exception when trying to run the report from my client.


The Exception

Message:

Handler dispatch failed; nested exception is java.lang.AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(Ljava/lang/String;Z)V

Description:

The server encountered an internal error that prevented it from fulfilling this request.

Exception:

org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(Ljava/lang/String;Z)V
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:982)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)

Root cause:

java.lang.AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(Ljava/lang/String;Z)V
net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.<init>(SimpleFontExtensionHelper.java:149)
net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.getInstance(SimpleFontExtensionHelper.java:131)
net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.ensureFontExtensions(FontExtensionsRegistry.java:80)
net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.getExtensions(FontExtensionsRegistry.java:57)
net.sf.jasperreports.extensions.DefaultExtensionsRegistry.getExtensions(DefaultExtensionsRegistry.java:115)
net.sf.jasperreports.engine.util.JRStyledTextParser.<clinit>(JRStyledTextParser.java:86)
net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:110)
net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:69)
net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:57)
net.sf.jasperreports.engine.fill.JRFiller.createBandReportFiller(JRFiller.java:200)
net.sf.jasperreports.engine.fill.JRFiller.createReportFiller(JRFiller.java:215)
net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:115)
net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:667)
net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:648)
net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:970)

Answer:

The error indicates that you have an old DOM/SAX implementation in your project.

You might have a direct or transitive dependency to a parser such as Xerces.

You should either upgrade the dependency to a newer version, or remove/exclude it so that the parser included in the JRE is used.

Question:


Answer:

As Alex K. pointed out, the best way to change attributes with a Java application is to create the Reports with the Jasper Reports API.

For example in one answer to http://community.jaspersoft.com/questions/525188/dynamic-width-textfied-parameter the width of an object was changed before the report was generated:

JasperDesign design = xmlLoader.loadXML(..jrxmlStream..);
JRElement[] elements = design.getDetail().getElements();
String elementKey = ..key of element to modify..;
int newWidth = ..new element width..;
for (int i = 0; i < elements.length; i++)
{
    JRDesignElement element = (JRDesignElement) elements[i];
    if (elementKey.equals(element.getKey())) {
        element.setWidth(newWidth);
    }
}

You can use additionally setHeight, setX() and setY() to change the elements properties.

More information is provided here: http://community.jaspersoft.com/wiki/jasperreports-library-reference-materials

Question:

I've got an existing dynamic jasper report that I need to modify so that the page orientation and size can be set dynamically. I've been able to achieve this using the dynamicReportBuilder.setPageSizeAndOrientation(...). The trouble is that when I change page sizes the title is no longer in the middle of the page...

I'm defining the title like:

<title>
    <band height="20" splitType="Stretch">
        <textField>
            <reportElement x="0" y="0" width="760" height="20"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">
                <font fontName="ConjectSans" size="14" isBold="false"/>
            </textElement>
            <textFieldExpression><![CDATA[$P{title}]]>    
            </textFieldExpression>
        </textField>
    </band>
</title>

Is there any way I can change the above so that the title text will float to the middle of the page regardless of what size I set the page?

From what I've googled I I can't set the width attribute dynamically in the jrxml, instead I need to do something like:

JRElement element = jasperReport.getTitle().getElementByKey("graphWidthKey");
element.setWidth(100);

But how do I get access to the JasperReport object from the dynamic Jasper's DynamicReportBuilder?


Answer:

You cannot do that. the JasperReport object is a read-only object. It is the result of compiling the JasperDesign object.

Being able to set up the page size programatically makes it dynamic! if you need to change it again, then generate the report again.

Question:


Answer:

You should have below libraries to run typical Jasper report.

Question:

<bean id="pdf" class="org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView"
          p:url="classpath:jasperReports/test.jrxml"
          p:reportDataKey="datasource" />

Trying to convert the above code to annoted @Bean but failed to do. Any suggestions


Answer:

Haven't tested it, but just create the object and set the attributes. Any specifics/error messages when you try to autowire it?

@Bean
public JasperReportsPdfView getJasperReports(){
    JasperReportsPdfView view = new JasperReportsPdfView();
    view.setUrl("classpath:jasperReports/test.jrxml");
    view.setReportDataKey("datasource");
    return view;
}

Question:

Hi i'm new to jasper report.i'm using ireport for designing report. I have created a simple report design, which have 2 fields name,addr.

public class R {
     private String name;
      private String addr;

      public R(String name, String addr) {
       super();
       this.name = name;
       this.addr = addr;
      }
      public String getName() {
       return name;
      }
      public void setName(String name) {
       this.name = name;
      }
      public String getAddr() {
       return addr;
      }
      public void setAddr(String addr) {
       this.addr = addr;
      }
} 

.jrxml file

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="R" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="4fd2f78e-344d-4371-ba1e-f86c2a81ef75">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch"/>
    </title>
    <pageHeader>
        <band height="35" splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band height="61" splitType="Stretch">
            <staticText>
                <reportElement x="296" y="41" width="228" height="20" uuid="19aa39a0-45cf-4b36-b327-25b640f81d8a"/>
                <textElement textAlignment="Center"/>
                <text><![CDATA[Address]]></text>
            </staticText>
            <staticText>
                <reportElement x="36" y="41" width="215" height="20" uuid="baba8372-2215-439d-8b20-fd4ab054bbe5"/>
                <textElement textAlignment="Center"/>
                <text><![CDATA[Name]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="125" splitType="Stretch">
            <textField>
                <reportElement x="296" y="0" width="228" height="20" uuid="c4de17e6-e5bc-4454-b38e-cc50acf18f0b"/>
                <textFieldExpression><![CDATA[$F{addr}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="36" y="0" width="215" height="20" uuid="8283d8b6-a288-48ec-bd4a-36c2875f5cff"/>
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="54" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="42" splitType="Stretch"/>
    </summary>
</jasperReport>

Here i'm using array list as a data source. When i click compile button on i report it shows error that

net.sf.jasperreports.engine.design.JRValidationException: Report design not valid :       1. Field not found : addr      2. Field not found : name

java code

public void runReport(String fileName, String outFileName) throws JRException 
     {

       List<R> list = new ArrayList<R>();

       Map parameters = new HashMap();
       list.add(new R("a1" ,"a2"));
       list.add(new R("b1" ,"b2"));
       list.add(new R("c1" ,"c2"));

       JasperPrint print = JasperFillManager.fillReport( fileName, parameters, new JRBeanCollectionDataSource(list));
                JRExporter exporter = new JRPdfExporter();
                exporter.setParameter(
                JRExporterParameter.OUTPUT_FILE_NAME,outFileName);
                exporter.setParameter(
                JRExporterParameter.JASPER_PRINT, print);
                JasperExportManager.exportReportToPdfFile(print, outFileName);
                print = null;
                exporter = null;

        }

Answer:

You should add to your jrxml field:

<field name="addr" class="java.lang.String">
    <fieldDescription><![CDATA[addr]]></fieldDescription></field>

You can do it by clicking on "fields" and selecting "create field".

Question:


Answer:

Compiling a JRXML converts it in a regular java class that lives in your classpath. So it has access to all your classpath objects.

To access to a member function you just need to specify it's absolute name inside of your report. So:

  1. Ensure your NumToWork class lives inside your source classpath.
  2. Change your JRXML to reference this class absolutely:
<textFieldExpression><![CDATA[org.eduadvent.reportes.NumToWord.convert(1)]]></textFieldExpression>

Question:

I am using JasperReports in order to create a reports on an Java web application using tomcat, but I am facing this error which I was not able to quite find a solution on Google. The only topics that I found talked about to add Xerces to the dependencys which I have done but still not changed a thing.

String reportOutput = reportOutputLocation+reportName;
InputStream reportTemplate = getClass().getClassLoader().getResourceAsStream(reportSrcLocation);
JasperDesign jasperDesign = JRXmlLoader.load(reportTemplate);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
Map<String, Object> paramObjects = new HashMap<String, Object>();
paramObjects.putAll(parameters);
JasperPrint jprint = JasperFillManager.fillReport(jasperReport, paramObjects, conn);

The error happens over here: JRXmlLoader.load(reportTemplate);

This is the stack trace output:

net.sf.jasperreports.engine.JRRuntimeException: Error creating SAX parser
net.sf.jasperreports.engine.xml.BaseSaxParserFactory.createParser(BaseSaxParserFactory.java:99)
net.sf.jasperreports.engine.xml.JRXmlDigesterFactory.createParser(JRXmlDigesterFactory.java:1456)
net.sf.jasperreports.engine.xml.JRXmlDigesterFactory.createDigester(JRXmlDigesterFactory.java:1432)
net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:262)
net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:247)
java.lang.Thread.run(Unknown Source)

<jasper.version>5.6.1</jasper.version>
 <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.9.1</version>
</dependency> 

Answer:

As I knew the code was working fine and the issue was in the project setup. The pom.xml was fine and also the dependencys.

What I did in order to get this working was double click on tomcat server on Eclipse.

- Download xercesImpl-2.8.1.jar or any other version
- Click on "Open Launch Configuration"
- Go to the tab "Classpath"
- Click on Bootstrap Entries
- Add External JARs
- Select xercesImpl-2.8.1.jar or any version that you prefer.

Restart server and it should work.

Question:

The following is my Report.jrxml file. I have an ArrayList of a custom class which has parameters createdOn,actionby etc and I wish to populate the report based on it.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.2.0.final using JasperReports Library version 6.2.0  -->
<!-- 2015-12-21T18:21:11 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="_blank" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ced95029-b569-4027-895c-af2843a4e088">
    <property name="com.jaspersoft.studio.data.sql.tables" value=""/>
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <parameter name="logotwo" class="java.lang.String"/>
    <parameter name="logo" class="java.lang.String"/>
    <style name="Title" fontName="Times New Roman" fontSize="50" isBold="true"/>
    <style name="SubTitle" forecolor="#03A9F4" fontName="Arial" fontSize="18"/>
    <style name="Column header" forecolor="#666666" fontName="Arial" fontSize="12" isBold="true"/>
    <style name="Detail" fontName="Times New Roman" fontSize="12"/>
    <style name="Row" mode="Opaque" fontName="Times New Roman" fontSize="12">
        <conditionalStyle>
            <conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
            <style backcolor="#000000"/>
        </conditionalStyle>
    </style>
    <field name="filePath" class="java.lang.String"/>
    <field name="createdOn" class="java.sql.Date"/>
    <field name="actionby" class="java.lang.Integer"/>
    <field name="actionType" class="java.lang.String"/>
    <sortField name="createdOn"/>
    <group name="Group1">
        <groupExpression><![CDATA[$F{createdOn}]]></groupExpression>
        <groupHeader>
            <band height="37">
                <frame>
                    <reportElement mode="Transparent" x="-21" y="7" width="597" height="24" forecolor="#B89F7D" backcolor="#F2EBDF" uuid="df26104b-a7fc-458f-8a21-50b13c7c7736"/>
                    <rectangle>
                        <reportElement mode="Transparent" x="21" y="0" width="36" height="24" backcolor="#03A9F4" uuid="369745f3-8095-4b8b-8b7a-38e42b7aef67"/>
                        <graphicElement>
                            <pen lineWidth="0.0"/>
                        </graphicElement>
                    </rectangle>
                    <textField pattern="dd-MM-yyyy">
                        <reportElement style="SubTitle" x="10" y="0" width="413" height="24" forecolor="#E50000" uuid="ef0a10c7-2940-4ac1-a69e-db1a00ae6f2e"/>
                        <textElement>
                            <font isBold="true"/>
                        </textElement>
                        <textFieldExpression><![CDATA[$F{createdOn}]]></textFieldExpression>
                    </textField>
                </frame>
            </band>
        </groupHeader>
        <groupFooter>
            <band height="6"/>
        </groupFooter>
    </group>
    <background>
        <band height="802" splitType="Stretch">
            <image hAlign="Center">
                <reportElement mode="Transparent" x="150" y="372" width="200" height="200" uuid="42c96db8-4afd-4834-ba69-6b211df0c42f"/>
                <imageExpression><![CDATA[$P{logotwo}]]></imageExpression>
            </image>
        </band>
    </background>
    <title>
        <band height="136" splitType="Stretch">
            <image>
                <reportElement x="0" y="0" width="164" height="126" uuid="ddc15723-2728-421f-b95e-2df9faf64ce1"/>
                <imageExpression><![CDATA[$P{logo}]]></imageExpression>
            </image>
            <staticText>
                <reportElement style="Title" x="170" y="0" width="230" height="60" uuid="1a652692-054a-40f3-ade5-68d8da36626d"/>
                <textElement verticalAlignment="Middle"/>
                <text><![CDATA[Report]]></text>
            </staticText>
            <staticText>
                <reportElement style="SubTitle" x="219" y="62" width="196" height="22" uuid="88d4231e-f014-4b0d-b871-1737ba63a1ae"/>
                <textElement>
                    <font fontName="Times New Roman"/>
                </textElement>
                <text><![CDATA[Activity Report]]></text>
            </staticText>
            <staticText>
                <reportElement x="172" y="94" width="383" height="42" uuid="f0bfb1ea-a85a-47cd-a1a4-43f22b45e80f"/>
                <textElement textAlignment="Right">
                    <font size="10"/>
                </textElement>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band height="16" splitType="Stretch">
            <line>
                <reportElement positionType="FixRelativeToBottom" x="0" y="15" width="555" height="1" uuid="1a61a836-d137-48b1-ad67-6ff64600bf93"/>
                <graphicElement>
                    <pen lineWidth="0.5" lineColor="#999999"/>
                </graphicElement>
            </line>
            <staticText>
                <reportElement style="Column header" x="20" y="0" width="100" height="15" forecolor="#03A9F4" uuid="8093e6b6-1479-4d7e-a3e1-8b43ac16fe34"/>
                <text><![CDATA[User]]></text>
            </staticText>
            <staticText>
                <reportElement style="Column header" x="120" y="0" width="138" height="15" forecolor="#03A9F4" uuid="c9463f8f-ce24-4798-9f83-1122da0d5f31"/>
                <text><![CDATA[File Path]]></text>
            </staticText>
            <staticText>
                <reportElement style="Column header" x="400" y="0" width="138" height="15" forecolor="#03A9F4" uuid="cfb1f8c6-3240-4393-be47-70b56eea3926"/>
                <text><![CDATA[Action Type]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="15" splitType="Stretch">
            <frame>
                <reportElement style="Row" mode="Transparent" x="0" y="0" width="555" height="15" forecolor="#009688" uuid="a98495d8-3c8d-4fa0-81f5-30c3efc2f766"/>
                <textField isStretchWithOverflow="true">
                    <reportElement style="Detail" x="20" y="0" width="100" height="15" forecolor="#009688" uuid="714380ba-f273-4f2c-9a24-e01f345aeb03"/>
                    <textFieldExpression><![CDATA[$F{actionby}]]></textFieldExpression>
                </textField>
                <textField isStretchWithOverflow="true">
                    <reportElement style="Detail" x="120" y="0" width="250" height="15" forecolor="#009688" uuid="e7d518fc-f335-40ab-acc1-8858f53a806e"/>
                    <textFieldExpression><![CDATA[$F{filePath}]]></textFieldExpression>
                </textField>
                <textField isStretchWithOverflow="true">
                    <reportElement style="Detail" x="400" y="0" width="150" height="15" forecolor="#009688" uuid="34a6eb4a-7c05-4129-815e-ae1153f52798"/>
                    <textFieldExpression><![CDATA[$F{actionType}]]></textFieldExpression>
                </textField>
            </frame>
        </band>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch">
            <line>
                <reportElement positionType="FixRelativeToBottom" x="0" y="3" width="555" height="1" uuid="fa45a887-615a-4d84-a2d7-8a2219671b3c"/>
                <graphicElement>
                    <pen lineWidth="0.5" lineColor="#999999"/>
                </graphicElement>
            </line>
        </band>
    </columnFooter>
    <pageFooter>
        <band height="25" splitType="Stretch">
            <frame>
                <reportElement mode="Transparent" x="-21" y="1" width="597" height="24" forecolor="#D0B48E" backcolor="#F2EBDF" uuid="183682bc-d976-4756-83e0-6625a3f98ed1"/>
                <textField evaluationTime="Report">
                    <reportElement style="Column header" x="533" y="0" width="40" height="20" forecolor="#03A9F4" uuid="0193f9b3-1559-491a-8580-b6988863b6a1"/>
                    <textElement verticalAlignment="Middle">
                        <font size="10" isBold="false"/>
                    </textElement>
                    <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
                </textField>
                <textField>
                    <reportElement style="Column header" x="453" y="0" width="80" height="20" forecolor="#03A9F4" uuid="d00b105e-494b-418b-8ac9-8b1b4824f4f0"/>
                    <textElement textAlignment="Right" verticalAlignment="Middle">
                        <font size="10" isBold="false"/>
                    </textElement>
                    <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
                </textField>
                <textField pattern="EEEEE dd MMMMM yyyy">
                    <reportElement style="Column header" x="22" y="1" width="197" height="20" forecolor="#03A9F4" uuid="0616f3fe-0354-456f-8911-ec30ec51a5ae"/>
                    <textElement verticalAlignment="Middle">
                        <font size="10" isBold="false"/>
                    </textElement>
                    <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
                </textField>
            </frame>
        </band>
    </pageFooter>
    <summary>
        <band splitType="Stretch"/>
    </summary>
</jasperReport>

NOTE : I have added the parameters on my own ie logo and logotwo and the parsing errors started when I did so. I have serious doubts whether it is based on them.

Anyways,when I try running my project , I get this error.

net.sf.jasperreports.engine.JRException: org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 78; cvc-complex-type.2.4.a: Invalid content was found starting with element 'style'. One of '{"http://jasperreports.sourceforge.net/jasperreports":parameter, "http://jasperreports.sourceforge.net/jasperreports":queryString, "http://jasperreports.sourceforge.net/jasperreports":field, "http://jasperreports.sourceforge.net/jasperreports":sortField, "http://jasperreports.sourceforge.net/jasperreports":variable, "http://jasperreports.sourceforge.net/jasperreports":filterExpression, "http://jasperreports.sourceforge.net/jasperreports":group, "http://jasperreports.sourceforge.net/jasperreports":background, "http://jasperreports.sourceforge.net/jasperreports":title, "http://jasperreports.sourceforge.net/jasperreports":pageHeader, "http://jasperreports.sourceforge.net/jasperreports":columnHeader, "http://jasperreports.sourceforge.net/jasperreports":detail, "http://jasperreports.sourceforge.net/jasperreports":columnFooter, "http://jasperreports.sourceforge.net/jasperreports":pageFooter, "http://jasperreports.sourceforge.net/jasperreports":lastPageFooter, "http://jasperreports.sourceforge.net/jasperreports":summary, "http://jasperreports.sourceforge.net/jasperreports":noData}' is expected.
    at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:302)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:285)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:274)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:248)
    at net.sf.jasperreports.engine.JasperCompileManager.compile(JasperCompileManager.java:341)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:608)
    at com.ram.report.ReportGen.execute(ReportGen.java:103)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    at com.vmr.general.actions.login.LoginInterceptor.intercept(LoginInterceptor.java:905)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:249)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:249)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 78; cvc-complex-type.2.4.a: Invalid content was found starting with element 'style'. One of '{"http://jasperreports.sourceforge.net/jasperreports":parameter, "http://jasperreports.sourceforge.net/jasperreports":queryString, "http://jasperreports.sourceforge.net/jasperreports":field, "http://jasperreports.sourceforge.net/jasperreports":sortField, "http://jasperreports.sourceforge.net/jasperreports":variable, "http://jasperreports.sourceforge.net/jasperreports":filterExpression, "http://jasperreports.sourceforge.net/jasperreports":group, "http://jasperreports.sourceforge.net/jasperreports":background, "http://jasperreports.sourceforge.net/jasperreports":title, "http://jasperreports.sourceforge.net/jasperreports":pageHeader, "http://jasperreports.sourceforge.net/jasperreports":columnHeader, "http://jasperreports.sourceforge.net/jasperreports":detail, "http://jasperreports.sourceforge.net/jasperreports":columnFooter, "http://jasperreports.sourceforge.net/jasperreports":pageFooter, "http://jasperreports.sourceforge.net/jasperreports":lastPageFooter, "http://jasperreports.sourceforge.net/jasperreports":summary, "http://jasperreports.sourceforge.net/jasperreports":noData}' is expected.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:458)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3237)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1796)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(XMLSchemaValidator.java:766)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:356)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2786)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:648)
    at org.apache.commons.digester.Digester.parse(Digester.java:1892)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:298)
    ... 83 more

When I looked up at the Markers tab in Eclipse, I found that there were errors in line 9 and 13 which had similar errors

Description Resource    Path    Location    Type
cvc-complex-type.2.4.a: Invalid content was found starting with element 'style'. One of '{"http://jasperreports.sourceforge.net/jasperreports":parameter, "http://jasperreports.sourceforge.net/jasperreports":queryString, "http://jasperreports.sourceforge.net/jasperreports":field, "http://jasperreports.sourceforge.net/jasperreports":sortField, "http://jasperreports.sourceforge.net/jasperreports":variable, "http://jasperreports.sourceforge.net/jasperreports":filterExpression, "http://jasperreports.sourceforge.net/jasperreports":group, "http://jasperreports.sourceforge.net/jasperreports":background, "http://jasperreports.sourceforge.net/jasperreports":title, "http://jasperreports.sourceforge.net/jasperreports":pageHeader, "http://jasperreports.sourceforge.net/jasperreports":columnHeader, "http://jasperreports.sourceforge.net/jasperreports":detail, "http://jasperreports.sourceforge.net/jasperreports":columnFooter, "http://jasperreports.sourceforge.net/jasperreports":pageFooter, "http://jasperreports.sourceforge.net/jasperreports":lastPageFooter, "http://jasperreports.sourceforge.net/jasperreports":summary, "http://jasperreports.sourceforge.net/jasperreports":noData}' is expected.   Report.jrxml    /vmr/src/com/ram/report/jasper  line 9  JRXML Problem

I had actually designed the .jrxml file with JasperStudio Plugin with Eclipse and edited the Coffee template to suit my needs.

This is a relevant snippet of my Action class code

               try
                {
                    System.out.println("coming to this method");
                    java.io.InputStream in = this.getClass().getClassLoader().getResourceAsStream("com/ram/report/jasper/Report.jrxml");
                    JasperReport jasperReport=JasperCompileManager.compileReport(in);
                    HashMap<String, Object> params = new HashMap<String, Object>();
                    params.put("logotwo", ClassLoader.getSystemResource("logo2.png").getPath());
                    params.put("logo", ClassLoader.getSystemResource("logo.png").getPath() );
                    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());
                    JasperViewer.viewReport(jasperPrint, false);

                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

I don't know what is wrong with this. Please help!


Answer:

Move your style tag's before parameter tag's

es.

<style name="Title" fontName="Times New Roman" fontSize="50" isBold="true"/>
<style name="SubTitle" forecolor="#03A9F4" fontName="Arial" fontSize="18"/>
<style name="Column header" forecolor="#666666" fontName="Arial" fontSize="12" isBold="true"/>
<style name="Detail" fontName="Times New Roman" fontSize="12"/>
<style name="Row" mode="Opaque" fontName="Times New Roman" fontSize="12">
    <conditionalStyle>
        <conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
        <style backcolor="#000000"/>
    </conditionalStyle>
</style>
<parameter name="logotwo" class="java.lang.String"/>
<parameter name="logo" class="java.lang.String"/>

For complete xsd see jasperreport.xsd

Question:

When I was running report in ireport I got output correctly. But when I compile jrml file through java code I am getting error like

org.xml.sax.SAXParseException; lineNumber: 63; columnNumber: 38; cvc-complex-type.2.4.d: Invalid content was found starting with element 'paragraph'. No child element is expected at this point.

Here is my java code

    public   byte[] generate(String path,String fileName,String type,String query,HashMap<String,Object> param){
        byte[] output=null;

            Connection con=JdbcUtil.getJdbcConnection();
            JasperDesign jasperDesign=null;
            JasperReport jasperReport=null;
            System.out.println("Exec RT");
            try{

             jasperDesign = JRXmlLoader.load(path+"\\"+fileName);
            }catch(Exception e1){System.out.println("t0:"+e1.getMessage());
            System.out.println("RTMap:"+param);
            try{           
            JRDesignQuery nQuery=new JRDesignQuery();
            nQuery.setText(query);
            jasperDesign.setQuery(nQuery);
                            }catch(Exception e){System.out.println("t1:"+e.getMessage());}
            System.out.println("Compiling Report Designs");
            try{
                jasperReport =   JasperCompileManager.compileReport(path+"\\"+fileName);
            }catch(Exception e5){}
            JasperPrint jasperPrint=null;
            try{
             jasperPrint = JasperFillManager.fillReport(jasperReport, param, con);
            }catch(Exception e){System.out.println("RT0:"+e.getMessage());}
            String fName=fileName.substring(0,fileName.indexOf("."));

            JRExporter exporter= null;
            try{
            if(type.equalsIgnoreCase("pdf")){
                output=JasperExportManager.exportReportToPdf(jasperPrint);
            }else if(type.equalsIgnoreCase("html")){
                exporter = new JRHtmlExporter();
            }else if(type.equalsIgnoreCase("rtf")){
                exporter=new JRRtfExporter();
            }else if(type.equalsIgnoreCase("xls")){
                exporter  = new JRXlsExporter();
            }else if(type.equalsIgnoreCase("csv")){
                exporter=new JRCsvExporter();
            }
             output = exportReportToBytes(jasperPrint, exporter);
            }catch(Exception er){System.out.println("RT2:"+er.getMessage());
            } 
            }   
            return output;
    }

I have one sub report and one main report. I used ireport 4.0.2. My jrxml file (offerLetter.jrxml):

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="offerLetter" language="groovy" pageWidth="595" pageHeight="1417" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <style name="table">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 1_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 2">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 2_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 2_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 2_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 3">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 3_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 3_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 3_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 4">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 4_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 4_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 4_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 5">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 5_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 5_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 5_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 6">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 6_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 6_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 6_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 7">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 7_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 7_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table 7_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <parameter name="appid" class="java.lang.Integer">
        <defaultValueExpression><![CDATA[]]></defaultValueExpression>
    </parameter>
    <parameter name="logopath" class="java.lang.String"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String"/>
    <queryString>
        <![CDATA[SELECT  offer.INT_OFFERID,ecat.CHR_CATEGORYNAME,CONCAT(year(CURRENT_TIMESTAMP),CONCAT('-',year(CURRENT_TIMESTAMP)+1)) ayear,
DATE_FORMAT(CURRENT_DATE,'%d-%b-%y'),
CONCAT( if(app.CHR_GENDER='Male','Mr. ', if(app.CHR_MARITALSTATUS ='M','Mrs.' ,'Ms.') ),' ',app.CHR_APPNAME) salute,office.CHR_OFFICENAME,desig.CHR_DESIGNAME,
DATE_ADD(CURDATE(),INTERVAL 3 DAY) joining,
FUN_GET_takehome(hal.INT_APPID) takehome
FROM
 hrm_t_allowance hal,hrm_m_application app,hrm_t_offerletter offer,com_m_office office,com_m_desig desig,com_m_employeecategory ecat
 WHERE hal.INT_APPID=offer.INT_APPID AND app.INT_APPID=offer.INT_APPID AND offer.INT_DESIGID=desig.INT_DESIGID AND

offer.INT_OFFICEID=office.INT_OFFICEID AND hal.INT_APPID=$P{appid}
 AND ecat.INT_EMPLOYEECATEGORYID=offer.INT_CATEGORY;]]>
    </queryString>
    <field name="INT_OFFERID" class="java.lang.Integer"/>
    <field name="CHR_CATEGORYNAME" class="java.lang.String"/>
    <field name="ayear" class="java.lang.String"/>
    <field name="DATE_FORMAT(CURRENT_DATE,&apos;%d-%b-%y&apos;)" class="java.lang.String"/>
    <field name="salute" class="java.lang.String"/>
    <field name="CHR_OFFICENAME" class="java.lang.String"/>
    <field name="CHR_DESIGNAME" class="java.lang.String"/>
    <field name="joining" class="java.sql.Date"/>
    <field name="takehome" class="java.lang.Integer"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="84" splitType="Stretch">
            <image>
                <reportElement x="171" y="-1" width="360" height="58"/>
                <imageExpression class="java.lang.String"><![CDATA[$P{logopath}]]></imageExpression>
            </image>
            <staticText>
                <reportElement x="218" y="57" width="128" height="27"/>
                <textElement>
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[OFFER LETTER]]></text>
            </staticText>
        </band>
    </title>
    <summary>
        <band height="203" splitType="Stretch">
            <textField>
                <reportElement x="12" y="0" width="543" height="14"/>
                <box leftPadding="0" rightPadding="0"/>
                <textElement verticalAlignment="Top" markup="html">
                    <font fontName="Times New Roman" size="10"/>
                    <paragraph lineSpacing="1_1_2"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA["CARE/OFFER-"+$F{INT_OFFERID}+"/"+$F{CHR_CATEGORYNAME}+"/"+$F{ayear}+"."]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="12" y="14" width="100" height="14"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{DATE_FORMAT(CURRENT_DATE,'%d-%b-%y')}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="12" y="38" width="57" height="15"/>
                <textElement>
                    <font isBold="false"/>
                </textElement>
                <text><![CDATA[To,]]></text>
            </staticText>
            <textField>
                <reportElement x="12" y="53" width="100" height="15"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{salute}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="12" y="68" width="206" height="13"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{CHR_OFFICENAME}+","]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="12" y="98" width="543" height="14"/>
                <box leftPadding="0" rightPadding="0"/>
                <textElement verticalAlignment="Top" markup="html">
                    <font fontName="Times New Roman" size="10"/>
                    <paragraph lineSpacing="1_1_2"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA["Dear."+$F{salute}+","]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="12" y="112" width="543" height="16"/>
                <box leftPadding="0" rightPadding="0"/>
                <textElement verticalAlignment="Top" markup="html">
                    <font fontName="Times New Roman" size="10"/>
                    <paragraph lineSpacing="1_1_2"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA["We are pleased to offer the post of  "+" \""+$F{CHR_DESIGNAME}+" \" "+" in our organisation at "+"\""+$F{CHR_OFFICENAME}+"\""+"."]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="12" y="128" width="543" height="12"/>
                <box leftPadding="0" rightPadding="0"/>
                <textElement verticalAlignment="Top" markup="html">
                    <font fontName="Times New Roman" size="10"/>
                    <paragraph lineSpacing="1_1_2"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA["You are expected to join us on or before "+$F{joining}+" failing with this offer is not valid. Your salary details as mentioned bellow "]]></textFieldExpression>
            </textField>
            <subreport>
                <reportElement positionType="Float" x="12" y="140" width="41" height="38"/>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="appid">
                    <subreportParameterExpression><![CDATA[$P{appid}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="logopath">
                    <subreportParameterExpression><![CDATA[$P{logopath}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression class="java.lang.String"><![CDATA[$P{SUBREPORT_DIR} + "offerLetter_subreport1.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </summary>
</jasperReport>

Answer:

I got the result by deleting duplicated jasperreport jar files from the project

Question:

I'm getting this exception while compiling my jasper report which the exception is :

net.sf.jasperreports.engine.JRException: org.xml.sax.SAXException: http://java.sun.com/xml/jaxp/properties/schemaSource
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:247)
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:230)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:218)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:172)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:156)
at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:143)
at com.mhveranga.siripathi.utill.ReportGenerator.generateOrderInvoice(ReportGenerator.java:50)
at com.mhveranga.siripathi.utill.ReportGenerator.main(ReportGenerator.java:79)
Caused by: org.xml.sax.SAXException: http://java.sun.com/xml/jaxp/properties/schemaSource
at org.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1197)
at org.apache.commons.digester.Digester.parse(Digester.java:1647)
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:243)
... 7 more

Here is my XML file :

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="order" language="groovy" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" whenResourceMissingType="Empty">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="294"/>
    <parameter name="custID" class="java.lang.String"/>
    <parameter name="custContact" class="java.lang.String"/>
    <parameter name="custName" class="java.lang.String"/>
    <parameter name="custAddress" class="java.lang.String"/>
    <parameter name="orderID" class="java.lang.String"/>
    <parameter name="mobileBrand" class="java.lang.String"/>
    <parameter name="mobileModel" class="java.lang.String"/>
    <parameter name="mobileIMEI" class="java.lang.String"/>
    <parameter name="isBattery" class="java.lang.String"/>
    <parameter name="isCharger" class="java.lang.String"/>
    <parameter name="isSIM" class="java.lang.String"/>
    <parameter name="isMemory" class="java.lang.String"/>
    <parameter name="description" class="java.lang.String"/>
    <parameter name="note" class="java.lang.String"/>
    <parameter name="date" class="java.lang.String"/>
    <background>
        <band/>
    </background>
    <title>
        <band height="84">
            <staticText>
                <reportElement x="123" y="21" width="297" height="33"/>
                <textElement>
                    <font size="22" isBold="true"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[SIRIPATHI PHONE CENTER]]></text>
            </staticText>
            <line>
                <reportElement x="63" y="54" width="404" height="1"/>
            </line>
        </band>
    </title>
    <pageHeader>
        <band height="109">
            <staticText>
                <reportElement x="203" y="0" width="144" height="20"/>
                <textElement textAlignment="Center">
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Mahawaththe, Batapola]]></text>
            </staticText>
            <staticText>
                <reportElement x="224" y="20" width="103" height="21"/>
                <textElement>
                    <font size="16" isBold="true"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[077 600 1233]]></text>
            </staticText>
            <staticText>
                <reportElement x="203" y="77" width="157" height="20"/>
                <textElement>
                    <font size="12" isBold="true"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Software/Hardware/Unlock]]></text>
            </staticText>
            <staticText>
                <reportElement x="27" y="47" width="505" height="30"/>
                <textElement textAlignment="Center">
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[We repair all types of mobile phones in Siripathi Phone Center and we will guarantee all our repairs to be free of defects.]]></text>
            </staticText>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="36"/>
    </columnHeader>
    <detail>
        <band height="512">
            <staticText>
                <reportElement x="38" y="50" width="78" height="23"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Customer ID : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="119" width="90" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Customer Name : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="84" width="100" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Customer Contact : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="152" width="100" height="18"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Customer Address : ]]></text>
            </staticText>
            <line>
                <reportElement x="38" y="193" width="465" height="1"/>
            </line>
            <staticText>
                <reportElement x="38" y="213" width="62" height="16"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Order ID : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="244" width="100" height="17"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Mobile Brand : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="276" width="100" height="18"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Mobile Model : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="307" width="78" height="17"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Mobile IMEI : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="340" width="58" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Battery : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="170" y="340" width="56" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Charger : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="297" y="340" width="41" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[SIM : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="410" y="340" width="50" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Memory : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="372" width="78" height="16"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Description : ]]></text>
            </staticText>
            <staticText>
                <reportElement x="38" y="445" width="58" height="16"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Note : ]]></text>
            </staticText>
            <textField>
                <reportElement x="148" y="50" width="355" height="23"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{custID}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="148" y="84" width="355" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{custContact}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="148" y="119" width="355" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{custName}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="148" y="152" width="355" height="18"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{custAddress}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="148" y="213" width="355" height="16"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{orderID}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="148" y="244" width="355" height="17"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{mobileBrand}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="148" y="276" width="355" height="18"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{mobileModel}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="148" y="307" width="355" height="17"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{mobileIMEI}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="96" y="340" width="48" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{isBattery}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="227" y="340" width="42" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{isCharger}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="338" y="340" width="46" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{isSIM}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="460" y="340" width="52" height="19"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{isMemory}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="144" y="372" width="388" height="54"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{description}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="144" y="445" width="388" height="53"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{note}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="38" y="14" width="78" height="23"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <text><![CDATA[Date :]]></text>
            </staticText>
            <textField>
                <reportElement x="148" y="17" width="355" height="20"/>
                <textElement>
                    <font size="12"/>
                    <paragraph lineSpacing="Single"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{date}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band height="9"/>
    </columnFooter>
    <pageFooter>
        <band height="9"/>
    </pageFooter>
    <summary>
        <band height="8"/>
    </summary>
</jasperReport>

Here are my dependencies related to Jasper in my pom.xml :

        <dependency>

            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>

            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils-core</artifactId>
            <version>1.8.3</version>

        </dependency>

        <dependency>

            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>

        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging-api</artifactId>
            <version>1.1</version>
        </dependency>


        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>commons-math</groupId>
            <artifactId>commons-math</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>commons-vfs</groupId>
            <artifactId>commons-vfs</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>1.7</version>
        </dependency>

       <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
                <groupId>com.lowagie</groupId>
                <artifactId>itext</artifactId>
                <version>2.1.7</version>
        </dependency>


        <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.0.1-FINAL</version>
        </dependency>

        <dependency>

            <groupId>com.google.code.maven-play-plugin.org.apache.commons</groupId>
            <artifactId>commons-javaflow</artifactId>
            <version>1209105</version>

        </dependency>

This is my java code :

try {
            JasperReport jr = JasperCompileManager.compileReport(reportSource);
            JasperPrint jp = JasperFillManager.fillReport(jr, param);
            JasperViewer.viewReport(jp);
        } catch (JRException ex) {
            Logger.getLogger(ReportGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }

I tried a lot to get this issue solved but i couldn't find proper support please help me if you have any idea about this. Thanks.


Answer:

I just figured out the issue after trying few days.

Initially the issue was that i have added the dependencies which jasperreports depends on one by one manually into my pom which I don't have to do. Then there have been conflicts. Only jasperreports and groovy dependencies are enough. If you don't use groovy you don't have to add that too.

But then later jasperreport said 'The document has no pages' even when I'm passing data through parameters. That is because i haven't used

JasperPrint jp = JasperFillManager.fillReport(jr, param, new JREmptyDataSource());

instead of

JasperPrint jp = JasperFillManager.fillReport(jr, param);

JasperReports doesn't have enough community support i had to figure this out by my self. Anyway i suggest that JasperReports library should be much improved.