如何将mongodb的连接对象提供给JasperFillManager.fillReport()-Spring MongoDB Jasper Integration [英] How to provide connection object of mongodb to JasperFillManager.fillReport() - Spring MongoDB Jasper Integration

查看:54
本文介绍了如何将mongodb的连接对象提供给JasperFillManager.fillReport()-Spring MongoDB Jasper Integration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Spring MongoDB Jasper 集成示例.我有一个 Spring Mysql Jasper 示例,它运行良好.我要转换为mongodb的相同程序.

I am working on the Spring MongoDB Jasper integration example. I've had the Spring Mysql Jasper example which is working fine. The same program I am looking to convert for the mongodb.

位于以下位置的源代码: https://github.com/test512/spring -mvc-mongo-jasper.git

Source code at : https://github.com/test512/spring-mvc-mongo-jasper.git

@注意:我关注了 http://jasperreports.sourceforge.net/api/index. html ,但是我看不到要下载的jar文件.它不存在于Maven回购中吗?

@Note: I followed http://jasperreports.sourceforge.net/api/index.html, but I dont see jar file to download. Its not present in maven repo?

LoadJasperReport.java

@Controller
public class LoadJasperReport {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoadJasperReport.class);

    @ModelAttribute("jasperRptFormats")
    public ArrayList<String> getJasperRptFormats() {
        ArrayList<String> jasperRptFormats = new ArrayList<String>();
        jasperRptFormats.add("Html");
        jasperRptFormats.add("PDF");

        return jasperRptFormats;
    }

    @RequestMapping(value = "/loadJasper", method = RequestMethod.GET)
    public String loadSurveyPg(@ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm, Model model) {
        model.addAttribute("JasperInputForm", jasperInputForm);
        return "loadJasper";
    }

    @RequestMapping(value = "/generateReport", method = RequestMethod.POST)
    public String generateReport(@Valid @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
            BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response)
            throws ParseException {
        LOGGER.debug("~~~ Generate Report ~~~");

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

        }

        String reportFileName = "JREmp1";

        Connection conn = null;
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                LOGGER.error("Please include Classpath Where your MySQL Driver is located");
                e.printStackTrace();
            }

            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            if (conn != null)
                LOGGER.debug("Database Connected");
            else
                LOGGER.debug(" connection Failed ");

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

            LOGGER.debug("rpt format " + rptFormat + ", 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 = getCompiledFile(reportFileName, request);

            if (rptFormat.equalsIgnoreCase("html")) {
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);
                // For HTML report
                generateReportHtml(jasperPrint, request, response);
            } else if (rptFormat.equalsIgnoreCase("pdf")) {
                // For PDF report
                generateReportPDF(response, hmParams, jasperReport, conn);
            }
        } catch (Exception sqlExp) {
            LOGGER.error("Exception::" + sqlExp.toString());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException expSQL) {
                LOGGER.error("SQLExp::CLOSING::" + expSQL.toString());
            }
        }
        return null;
    }

    private JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
        LOGGER.debug("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;
    }

    private void generateReportHtml(JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp)
            throws IOException, JRException {
        LOGGER.debug("~~~ Generate HTML Report ~~~");

        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();
    }

    private void generateReportPDF(HttpServletResponse resp, Map<String, Object> parameters, JasperReport jasperReport,
            Connection conn) throws JRException, NamingException, SQLException, IOException {
        LOGGER.debug("~~~ Generate PDF Report ~~~");

        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();
    }
}

我正尝试将MongoDB转换为如下所示的程序,但是我不确定如何获取Connection对象?有什么方法可以从mongodb中获取连接对象,也可以通过其他任何方式为mongodb jasper编写代码吗?

This program I am trying to convert for the MongoDB like below, but I am not sure how can I get the Connection object? Is there any way to get the connection object from the mongodb or any other way to write code for the mongodb jasper?

现在,我在行上看到了这个问题:

Now I see the issue at line :

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);

我更改了如下代码,但无法正常工作.请指导.

package net.javaonline.spring.jasper.controller;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jaspersoft.mongodb.MongoDbDataSource;
import com.jaspersoft.mongodb.connection.MongoDbConnection;

import net.javaonline.spring.jasper.form.JasperInputForm;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleHtmlReportConfiguration;

@Controller
public class LoadJasperReport {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoadJasperReport.class); 

    @ModelAttribute("jasperRptFormats")
    public ArrayList<String> getJasperRptFormats(){
        ArrayList<String> jasperRptFormats = new ArrayList<String>();
        jasperRptFormats.add("Html");
        jasperRptFormats.add("PDF");

        return jasperRptFormats;
    }   


    @RequestMapping(value = "/loadJasper", method = RequestMethod.GET)
    public String loadSurveyPg(
            @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
            Model model) {
        model.addAttribute("JasperInputForm", jasperInputForm);
        return "loadJasper";
    }


    @RequestMapping(value = "/generateReport", method = RequestMethod.POST)
    public String generateReport(
            @Valid @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
            BindingResult result,Model model, 
            HttpServletRequest request, HttpServletResponse response) throws ParseException {
        LOGGER.debug("~~~ Generate Report ~~~");

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

        }

        String reportFileName = "JREmp1";
        MongoDbConnection conn = null;

        try {
            try {
                conn = new MongoDbConnection("mongodb://localhost:27017/mydb", null, null);
            } catch (JRException e) {
                System.out.println("JREException : "+e.getMessage());
            }

            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put(MongoDbDataSource.QUERY_LANGUAGE, conn);

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

            LOGGER.debug("rpt format " + rptFormat+", 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 = getCompiledFile(reportFileName, request);

            if (rptFormat.equalsIgnoreCase("html") ) {
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);
                // For HTML report
                generateReportHtml(jasperPrint, request, response); 
            }
            else if(rptFormat.equalsIgnoreCase("pdf")){
                // For PDF report
                generateReportPDF(response, hmParams, jasperReport, conn); 
            }
        } catch (JRException | IOException | NamingException | SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            if (conn != null) {
                conn.close();
                conn = null;
            }
        }
        return null;
    }

    private JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
        LOGGER.debug("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;
    } 


    private void generateReportHtml( JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp) 
            throws IOException, JRException {
        LOGGER.debug("~~~ Generate HTML Report ~~~");

        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();
    }

    private void generateReportPDF (HttpServletResponse resp, Map<String, Object> parameters, 
            JasperReport jasperReport, Connection conn)throws JRException, NamingException, SQLException, IOException {
        LOGGER.debug("~~~ Generate PDF Report ~~~");

        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();
    } 
}

JREmp1.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="FirstReport" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="7ae7f135-7061-4947-be6e-66935e65141a">
    <property name="ireport.zoom" value="1.2100000000000006"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <queryString language="MongoDbQuery">
        <![CDATA[{ collectionName : 'oms_order' }]]>
    </queryString>
    <field name="Emp_code" class="java.lang.String"/>
    <field name="EmpName" class="java.lang.String"/>
    <field name="Salary" class="java.lang.Integer"/>
    <field name="Doj" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="31" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="555" height="27" uuid="52aef86d-1b56-49fa-bb20-e4b0ad93e554"/>
                <textElement textAlignment="Center">
                    <font size="15"/>
                </textElement>
                <text><![CDATA[OMS Order Report]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="435" y="0" width="80" height="20" uuid="1130b204-cf50-4ca0-a8ad-90377eb3c0f4"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Report">
                <reportElement x="515" y="0" width="40" height="20" uuid="9a913f85-d984-4d46-bc15-6223ad0746c3"/>
                <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="23" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20" uuid="14c1104f-267c-4a8e-90f9-4290ef574993"/>
                <text><![CDATA[buySideClientCode]]></text>
            </staticText>
            <staticText>
                <reportElement x="468" y="0" width="87" height="20" uuid="f4886a82-d127-4bd8-8561-8f4571763f98"/>
                <text><![CDATA[destId]]></text>
            </staticText>
            <staticText>
                <reportElement x="268" y="0" width="100" height="20" uuid="35a5e86f-5d4c-4be2-be09-e2629a2a089b"/>
                <text><![CDATA[orderAction]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="0" width="100" height="20" uuid="322fe843-6a8f-4e08-b4bd-15ebf89c4715"/>
                <text><![CDATA[clOrdID]]></text>
            </staticText>
            <staticText>
                <reportElement x="368" y="0" width="100" height="20" uuid="c1f05f4c-5f81-43c3-9861-f33d11692874"/>
                <text><![CDATA[orderID]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="23" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20" uuid="bce7874d-e031-4c70-86ed-22f6c0033561"/>
                <textFieldExpression><![CDATA[$F{buySideClientCode}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="468" y="0" width="87" height="20" uuid="87a25154-2e8c-4bb6-9ef3-a188577b04f6"/>
                <textFieldExpression><![CDATA[$F{destId}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="368" y="2" width="100" height="20" uuid="f65ef2db-2117-4bb1-92a6-ac1f0b2f18ef"/>
                <textFieldExpression><![CDATA[$F{orderID}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="2" width="100" height="20" uuid="88f63e67-0dd6-4e76-a428-c610b3d0ede0"/>
                <textFieldExpression><![CDATA[$F{clOrdID}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="268" y="3" width="100" height="20" uuid="52daf5f7-09e8-492d-bc46-2d5ebfd13838"/>
                <textFieldExpression><![CDATA[$F{orderAction}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band height="30" splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="19" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="22" splitType="Stretch"/>
    </summary>
</jasperReport>

推荐答案

无论如何,我现在能够解决此问题.您需要以下依赖项:

Anyway I was able to solve this issue now. You need below dependency:

<!-- but you need one more (secret) from mongoDB site -->
        <dependency>
            <groupId>com.jaspersoft.connectors.mongodb</groupId>
            <artifactId>js-mongodb-datasource</artifactId>
            <version>0.9.3</version>
        </dependency>

还有

<!-- This is a secret repository for js-mongodb-datasource jar -->
    <repositories>
        <repository>
            <id>MongoJasperRepo</id>
            <url>http://jaspersoft.artifactoryonline.com/jaspersoft/jaspersoft-repo</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>

,并使用了下面的代码. 完成了!

and just used the below code. Done !!

MongoDbConnection conn = null;

        try {
            try {
                conn = new MongoDbConnection("mongodb://" + mongoHost + ":" + mongoPort + "/" + mongodb, null, null);
            } catch (JRException e) {
                System.out.println("JREException : " + e.getMessage());
            }

这篇关于如何将mongodb的连接对象提供给JasperFillManager.fillReport()-Spring MongoDB Jasper Integration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆