Pracuję nad przykładem integracji Spring MongoDB Jasper z . Miałem przykład Spring Mysql Jasper, który działa poprawnie. Ten sam program, który zamierzam przekonwertować na mongodbę.Jak dostarczyć obiekt połączenia mongodb do JasperFillManager.fillReport() - Spring MongoDB Integracja Jaspera
kod źródłowy na: https://github.com/test512/spring-mvc-mongo-jasper.git
@note: Śledziłem http://jasperreports.sourceforge.net/api/index.html, ale nie widzę pliku jar do pobrania. Nie ma go w 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();
}
}
Ten program próbuję przekonwertować do MongoDB jak poniżej, ale nie jestem pewien, w jaki sposób można uzyskać obiektu Connection? Czy istnieje jakiś sposób na uzyskanie obiektu połączenia z mongody lub w inny sposób na napisanie kodu dla jaspisu mongotb?
Teraz widzę problemu na linii:
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);
Zmieniłem kod jak poniżej, ale to nie działa. Proszę przewodnika.
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>
można go downaload tutaj: https://github.com/soluvas/com.jaspersoft.studio.data.mongodb i nie jest też pom.xml gdzie należy znaleźć repozytorium –
Teraz mam com.jaspersoft.studio.data.mongodb-5.1.1-SNAPSHOT.jar na ścieżce klas. Ale teraz nie widzę MongoDbDataSource.CONNECTION nic w dowolnym pliku jar. Proszę przewodnika. Przesłałem kod src na https://github.com/test512/spring-mvc-mongo-jasper.git –