maven mysql转mongodb,如何将mongodb的连接对象提供给JasperFillManager.fillReport()-Spring MongoDB Jasper Integrati...

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.

@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 getJasperRptFormats() {

ArrayList jasperRptFormats = new ArrayList();

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 hmParams = new HashMap();

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 jasperPrintList = new ArrayList();

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

}

}

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

I changed code like below but its not working. Please guide.

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 getJasperRptFormats(){

ArrayList jasperRptFormats = new ArrayList();

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 parameters = new HashMap();

parameters.put(MongoDbDataSource.QUERY_LANGUAGE, conn);

String rptFormat = jasperInputForm.getRptFmt();

String noy = jasperInputForm.getNoofYears();

LOGGER.debug("rpt format " + rptFormat+", no of years " + noy);

HashMap hmParams=new HashMap();

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 jasperPrintList = new ArrayList();

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 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

685D6.png

解决方案

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

com.jaspersoft.connectors.mongodb

js-mongodb-datasource

0.9.3

And

MongoJasperRepo

http://jaspersoft.artifactoryonline.com/jaspersoft/jaspersoft-repo

true

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值