Java Code Examples for net.sf.jasperreports.engine.JasperReport

The following are top voted examples for showing how to use net.sf.jasperreports.engine.JasperReport. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pitanga-system   File: PgRelatorioDAO.java   View source code 8 votes vote down vote up
@Override
public JasperViewer gerarRelatorioClientesSintetico() {

    Connection connection = PostgreSQLDAOFactory.getConnection();

    try {
        Statement stm = connection.createStatement();
        String query = "SELECT\n"
                + "     cl.\"cod_cliente\" AS codigo,\n"
                + "     cl.\"nome_cliente\" AS nome,\n"
                + "     ci.\"nome_cidade\" AS nome_cidade,\n"
                + "     ci.\"sigla_uf\" AS sigla,\n"
                + "     cl.\"telefone\" AS telefone\n"
                + "FROM\n"
                + "     \"cliente\" cl INNER JOIN \"cidade\" ci "
                + "ON cl.\"cod_cidade\" = ci.\"cod_cidade\"\n"
                + "ORDER BY\n"
                + "     cl.nome_cliente ASC";

        ResultSet rs = stm.executeQuery(query);

        JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);

        InputStream fonte
                = PgRelatorioDAO.class.getResourceAsStream(
                        "/br/com/pitanga/report/RelatorioClientesSintetico.jrxml");

        JasperReport report = JasperCompileManager.compileReport(fonte);

        JasperPrint print = JasperFillManager.fillReport(report, null, jrRS);
        JasperViewer jv = new JasperViewer(print, false);

        return jv;

    } catch (JRException | SQLException ex) {
        throw new DAOException(
                "Falha ao gerar relatório sintético "
                + "de clientes em JDBCRelatorioDAO", ex);
    }
}
 
Example 2
Project: spring4-understanding   File: AbstractJasperReportsView.java   View source code 7 votes vote down vote up
/**
 * Checks to see that a valid report file URL is supplied in the
 * configuration. Compiles the report file is necessary.
 * <p>Subclasses can add custom initialization logic by overriding
 * the {@link #onInit} method.
 */
@Override
protected final void initApplicationContext() throws ApplicationContextException {
	this.report = loadReport();

	// Load sub reports if required, and check data source parameters.
	if (this.subReportUrls != null) {
		if (this.subReportDataKeys != null && this.subReportDataKeys.length > 0 && this.reportDataKey == null) {
			throw new ApplicationContextException(
					"'reportDataKey' for main report is required when specifying a value for 'subReportDataKeys'");
		}
		this.subReports = new HashMap<String, JasperReport>(this.subReportUrls.size());
		for (Enumeration<?> urls = this.subReportUrls.propertyNames(); urls.hasMoreElements();) {
			String key = (String) urls.nextElement();
			String path = this.subReportUrls.getProperty(key);
			Resource resource = getApplicationContext().getResource(path);
			this.subReports.put(key, loadReport(resource));
		}
	}

	// Convert user-supplied exporterParameters.
	convertExporterParameters();

	if (this.headers == null) {
		this.headers = new Properties();
	}
	if (!this.headers.containsKey(HEADER_CONTENT_DISPOSITION)) {
		this.headers.setProperty(HEADER_CONTENT_DISPOSITION, CONTENT_DISPOSITION_INLINE);
	}

	onInit();
}
 
Example 3
Project: jasperreports   File: AbstractTest.java   View source code 7 votes vote down vote up
public JasperReport compileReport(String jrxmlFileName) throws JRException, IOException
{
	JasperReport jasperReport = null;
	
	InputStream jrxmlInput = JRLoader.getResourceInputStream(jrxmlFileName);

	if (jrxmlInput != null)
	{
		JasperDesign design;
		try
		{
			design = JRXmlLoader.load(jrxmlInput);
		}
		finally
		{
			jrxmlInput.close();
		}
		jasperReport = JasperCompileManager.compileReport(design);
	}
	
	return jasperReport;
}
 
Example 4
Project: openbravo-brazil   File: RptC_OrderPO.java   View source code 7 votes vote down vote up
private void printPagePartePDF(HttpServletResponse response, VariablesSecureApp vars,
    String strcOrderId) throws IOException, ServletException {
  if (log4j.isDebugEnabled())
    log4j.debug("Output: pdf");
  String strLanguage = vars.getLanguage();
  String strBaseDesign = getBaseDesignPath(strLanguage);

  HashMap<String, Object> parameters = new HashMap<String, Object>();
  JasperReport jasperReportLines;
  try {
    jasperReportLines = ReportingUtils.compileReport(strBaseDesign
        + "/org/openbravo/erpReports/RptC_OrderPO_Lines.jrxml");
  } catch (JRException e) {
    e.printStackTrace();
    throw new ServletException(e.getMessage());
  }
  parameters.put("SR_LINES", jasperReportLines);
  parameters.put("ORDER_ID", strcOrderId);
  renderJR(vars, response, null, "pdf", parameters, null, null);
}
 
Example 5
Project: openbravo-brazil   File: RptM_Requisition.java   View source code 7 votes vote down vote up
private void printPagePartePDF(HttpServletResponse response, VariablesSecureApp vars,
    String strmRequisitionId) throws IOException, ServletException {
  if (log4j.isDebugEnabled())
    log4j.debug("Output: pdf");
  String strBaseDesign = getBaseDesignPath(vars.getLanguage());

  HashMap<String, Object> parameters = new HashMap<String, Object>();
  JasperReport jasperReportLines;
  try {
    jasperReportLines = ReportingUtils.compileReport(strBaseDesign
        + "/org/openbravo/erpReports/RptM_Requisition_Lines.jrxml");
  } catch (JRException e) {
    e.printStackTrace();
    throw new ServletException(e.getMessage());
  }

  parameters.put("SR_LINES", jasperReportLines);
  parameters.put("REQUISITION_ID", strmRequisitionId);
  renderJR(vars, response, null, "pdf", parameters, null, null);
}
 
Example 6
Project: Hotel-Properties-Management-System   File: ShowReport.java   View source code 6 votes vote down vote up
public void loadReport(String reportName, ReportObject reportObject) {

		logging = LoggingEngine.getInstance();
		
		try {
			
			final InputStream inputStream = ShowReport.class
					.getResourceAsStream("/com/coder/hms/reportTemplates/" + reportName + ".jrxml");
			JasperReport report = JasperCompileManager.compileReport(inputStream);

			HashMap<String, Object> parameters = new HashMap<String, Object>();	
			List<ReportObject> list = new ArrayList<ReportObject>();
			list.add(reportObject);
			JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(list);
			JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, beanColDataSource);
			final JRViewer viewer = new JRViewer(jasperPrint);

			setType(Type.POPUP);
			setResizable(false);
			setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
			this.setTitle("Reservation [Report]");
			this.setExtendedState(Frame.MAXIMIZED_BOTH);
			this.setAlwaysOnTop(isAlwaysOnTopSupported());
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			getContentPane().setLayout(new BorderLayout());
			this.setIconImage(Toolkit.getDefaultToolkit().
					getImage(LoginWindow.class.getResource(LOGOPATH)));
			this.setResizable(false);
			getContentPane().add(viewer, BorderLayout.CENTER);

		} catch (JRException e) {
			logging.setMessage("JRException report error!");
		}

	}
 
Example 7
Project: opencps-v2   File: JRReportUtil.java   View source code 6 votes vote down vote up
/**
 * @param jrxmlTemplate
 * @param jsonData
 * @param parameters
 * @param destFileName
 * @return
 */
public static String createReportFile(String jrxmlTemplate, String jsonData, Map<String, Object> parameters,
		String destFileName) {

	try {
		// fix json enter char
		jsonData = quoteHTML(jsonData);
		JasperReport reportTemplate = JRReportTemplate.getJasperReport(jrxmlTemplate);
		JRJSONDataSource dataSource = JRJSONDataSource.getInstance(jsonData);

		JasperPrint jasperPrint = getJasperPrint(reportTemplate, parameters, dataSource);

		return exportReport(jasperPrint, destFileName, DocType.PDF);
	} catch (Exception e) {
		_log.error(e);

		return StringPool.BLANK;

	}
}
 
Example 8
Project: opencps-v2   File: JRReportUtil.java   View source code 6 votes vote down vote up
/**
 * @param jrxmlTemplate
 * @param jsonData
 * @param parameters
 * @param outputDestination
 * @param exportName
 * @return
 */
public static String createReportPDFFile(String jrxmlTemplate, String jsonData, Map<String, Object> parameters,
		String outputDestination, String exportName) {

	String sourceFileName = outputDestination + exportName;
	try {
		// fix json enter char
		jsonData = quoteHTML(jsonData);
		JasperReport reportTemplate = JRReportTemplate.getJasperReport(jrxmlTemplate);
		JRJSONDataSource dataSource = JRJSONDataSource.getInstance(jsonData);

		JasperPrint jasperPrint = getJasperPrint(reportTemplate, parameters, dataSource);

		return exportPdfFile(jasperPrint, sourceFileName);
	} catch (Exception e) {
		_log.error(e);

		return StringPool.BLANK;

	}
}
 
Example 9
Project: Automekanik   File: ShikoPunetPunetoret.java   View source code 6 votes vote down vote up
private void krijoRaport(String pnt){
    btnRaporti.setOnAction(e -> {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                    HashMap hm = new HashMap();
                    hm.put("Folderi", folderi);
                    hm.put("punetori", pnt);
                    JasperReport jreport = JasperCompileManager.compileReport(raportiPunetor);
                    JasperPrint jprint = JasperFillManager.fillReport(jreport, hm, conn);
                    JasperViewer.viewReport(jprint, false);
                    conn.close();
                }catch (Exception ex){ex.printStackTrace();}
            }
        });
        t.start();
    });
}
 
Example 10
Project: spring4-understanding   File: AbstractJasperReportsView.java   View source code 6 votes vote down vote up
/**
 * Expose current Spring-managed Locale and MessageSource to JasperReports i18n
 * ($R expressions etc). The MessageSource should only be exposed as JasperReports
 * resource bundle if no such bundle is defined in the report itself.
 * <p>The default implementation exposes the Spring RequestContext Locale and a
 * MessageSourceResourceBundle adapter for the Spring ApplicationContext,
 * analogous to the {@code JstlUtils.exposeLocalizationContext} method.
 * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
 * @see org.springframework.context.support.MessageSourceResourceBundle
 * @see #getApplicationContext()
 * @see net.sf.jasperreports.engine.JRParameter#REPORT_LOCALE
 * @see net.sf.jasperreports.engine.JRParameter#REPORT_RESOURCE_BUNDLE
 * @see org.springframework.web.servlet.support.JstlUtils#exposeLocalizationContext
 */
protected void exposeLocalizationContext(Map<String, Object> model, HttpServletRequest request) {
	RequestContext rc = new RequestContext(request, getServletContext());
	Locale locale = rc.getLocale();
	if (!model.containsKey(JRParameter.REPORT_LOCALE)) {
		model.put(JRParameter.REPORT_LOCALE, locale);
	}
	TimeZone timeZone = rc.getTimeZone();
	if (timeZone != null && !model.containsKey(JRParameter.REPORT_TIME_ZONE)) {
		model.put(JRParameter.REPORT_TIME_ZONE, timeZone);
	}
	JasperReport report = getReport();
	if ((report == null || report.getResourceBundle() == null) &&
			!model.containsKey(JRParameter.REPORT_RESOURCE_BUNDLE)) {
		model.put(JRParameter.REPORT_RESOURCE_BUNDLE,
				new MessageSourceResourceBundle(rc.getMessageSource(), locale));
	}
}
 
Example 11
Project: spring4-understanding   File: AbstractJasperReportsView.java   View source code 6 votes vote down vote up
/**
 * Fill the given report using the given JDBC DataSource and model.
 */
private JasperPrint doFillReport(JasperReport report, Map<String, Object> model, DataSource ds) throws Exception {
	// Use the JDBC DataSource.
	if (logger.isDebugEnabled()) {
		logger.debug("Filling report using JDBC DataSource [" + ds + "]");
	}
	Connection con = ds.getConnection();
	try {
		return JasperFillManager.fillReport(report, model, con);
	}
	finally {
		try {
			con.close();
		}
		catch (Throwable ex) {
			logger.debug("Could not close JDBC Connection", ex);
		}
	}
}
 
Example 12
Project: ESIPC   File: Menu.java   View source code 6 votes vote down vote up
private void jMenuItem14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem14ActionPerformed
    // TODO add your handling code here:
   try {
        conectar cc= new conectar();
        
        JasperReport reportes=JasperCompileManager.compileReport("Curso.jrxml");
        JasperPrint print=JasperFillManager.fillReport(reportes, null, cc.conexion());
        JasperViewer.viewReport(print);
        
    } catch (Exception e) {
        System.out.printf(e.getMessage());
    }
}
 
Example 13
Project: OSCAR-ConCert   File: ManageLetters.java   View source code 6 votes vote down vote up
public static String[] getReportParams(JasperReport  jasperReport){
    JRParameter[] jrp =  jasperReport.getParameters();

    ArrayList<String> list = new ArrayList<String>();
    if(jrp != null){
        for (int i = 0 ; i < jrp.length; i++){
            if(!jrp[i].isSystemDefined()){
                list.add(jrp[i].getName());
                MiscUtils.getLogger().debug("JRP "+i+" :"+jrp[i].getName());
            }
        }

    }
    String[] s = new String[list.size()];
    return list.toArray(s);
}
 
Example 14
Project: openbravo-brazil   File: ReportingUtils.java   View source code 6 votes vote down vote up
/**
 * Generates sub-reports and adds them into the parameter map.
 * 
 * @param templateFile
 *          The path to the JR template of the report.
 * @param parameters
 *          The parameters to be sent to Jasper Report.
 * @param baseDesignPath
 *          Base design path.
 * @param connectionProvider
 *          A connection provider in case the report needs it.
 * @param language
 *          Language to be used when generating the sub-report.
 * @throws OBException
 *           In case there is any error generating the sub-reports an exception is thrown with the
 *           error message.
 */
private static void processSubReports(String templateFile, Map<String, Object> parameters,
    String baseDesignPath, ConnectionProvider connectionProvider, String language)
    throws OBException {
  try {
    JasperDesign jasperDesign = JRXmlLoader.load(templateFile);

    Object[] parameterList = jasperDesign.getParametersList().toArray();
    String parameterName = "";
    String subReportName = "";
    Collection<String> subreportList = new ArrayList<String>();
    File template = new File(templateFile);
    String templateLocation = template.getParent() + "/";

    /*
     * TODO: At present this process assumes the subreport is a .jrxml file. Need to handle the
     * possibility that this subreport file could be a .jasper file.
     */
    for (int i = 0; i < parameterList.length; i++) {
      final JRDesignParameter parameter = (JRDesignParameter) parameterList[i];
      if (parameter.getName().startsWith("SUBREP_")) {
        parameterName = parameter.getName();
        subreportList.add(parameterName);
        subReportName = Replace.replace(parameterName, "SUBREP_", "") + ".jrxml";
        JasperReport jasperReportLines = createSubReport(templateLocation, subReportName,
            baseDesignPath, connectionProvider, language);
        parameters.put(parameterName, jasperReportLines);
      }
    }

  } catch (final JRException e) {
    log.error("Error processing subreports for template: " + templateFile, e);
    throw new OBException(e.getMessage(), e);
  }
}
 
Example 15
Project: openbravo-brazil   File: GridBO.java   View source code 6 votes vote down vote up
private static JasperPrint createJasperPrint(InputStream reportFile,
    org.openbravo.erpCommon.utility.GridReportVO gridReportVO) throws JRException, IOException {
  JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
  if (log4j.isDebugEnabled())
    log4j.debug("Create JasperDesign");
  org.openbravo.erpCommon.utility.ReportDesignBO designBO = new org.openbravo.erpCommon.utility.ReportDesignBO(
      jasperDesign, gridReportVO);
  designBO.define();
  if (log4j.isDebugEnabled())
    log4j.debug("JasperDesign created, pageWidth: " + jasperDesign.getPageWidth()
        + " left margin: " + jasperDesign.getLeftMargin() + " right margin: "
        + jasperDesign.getRightMargin());
  JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
  Map<String, Object> parameters = new HashMap<String, Object>();
  parameters.put("BaseDir", gridReportVO.getContext());
  parameters.put("IS_IGNORE_PAGINATION", gridReportVO.getPagination());

  JasperPrint jasperPrint = JasperFillManager
      .fillReport(
          jasperReport,
          parameters,
          new JRFieldProviderDataSource(gridReportVO.getFieldProvider(), gridReportVO
              .getDateFormat()));
  return jasperPrint;
}
 
Example 16
Project: openbravo-brazil   File: RptC_Order.java   View source code 6 votes vote down vote up
private void printPagePartePDF(HttpServletResponse response, VariablesSecureApp vars,
    String strcOrderId) throws IOException, ServletException {

  if (log4j.isDebugEnabled())
    log4j.debug("Output: RptC_Order - pdf");
  RptCOrderHeaderData[] data = RptCOrderHeaderData.select(this, strcOrderId);
  if (log4j.isDebugEnabled())
    log4j.debug("data: " + (data == null ? "null" : "not null"));
  if (data == null || data.length == 0)
    data = RptCOrderHeaderData.set();

  String strLanguage = vars.getLanguage();
  String strBaseDesign = getBaseDesignPath(strLanguage);

  JasperReport jasperReportLines;
  try {
    jasperReportLines = ReportingUtils.compileReport(strBaseDesign
        + "/org/openbravo/erpReports/C_OrderLinesJR.jrxml");
  } catch (JRException e) {
    e.printStackTrace();
    throw new ServletException(e.getMessage());
  }

  HashMap<String, Object> parameters = new HashMap<String, Object>();
  parameters.put("SR_LINES", jasperReportLines);

  response.setHeader("Content-disposition", "inline; filename=SalesOrderJR.pdf");
  String strReportName = "@[email protected]/org/openbravo/erpReports/C_OrderJR.jrxml";
  renderJR(vars, response, strReportName, "pdf", parameters, data, null);
}
 
Example 17
Project: openbravo-brazil   File: RptC_Remittance.java   View source code 6 votes vote down vote up
private void printPagePDF(HttpServletResponse response, VariablesSecureApp vars,
    String strcRemittanceId, String language) throws IOException, ServletException {
  if (log4j.isDebugEnabled())
    log4j.debug("Output: pdf");

  String strBaseDesign = getBaseDesignPath(language);

  String strOutput = new String("pdf");

  String strReportName = "@[email protected]/org/openbravo/erpReports/RptC_Remittance.jrxml";

  if (strOutput.equals("pdf"))
    response.setHeader("Content-disposition", "inline; filename=RptC_Remittance.pdf");

  RptCRemittanceData[] data = RptCRemittanceData
      .select(this, Utility.getContext(this, vars, "#User_Client", "RptC_RemittanceJR"),
          Utility.getContext(this, vars, "#AccessibleOrgTree", "RptC_RemittanceJR"),
          strcRemittanceId);

  JasperReport jasperReportLines;
  try {
    jasperReportLines = ReportingUtils.getTranslatedJasperReport(this, strBaseDesign
        + "/org/openbravo/erpReports/RptC_Remittance_Lines.jrxml", vars.getLanguage(),
        strBaseDesign);
  } catch (JRException e) {
    e.printStackTrace();
    throw new ServletException(e.getMessage());
  }

  HashMap<String, Object> parameters = new HashMap<String, Object>();
  parameters.put("LANGUAGE", language);
  parameters.put("SR_LINES", jasperReportLines);

  renderJR(vars, response, strReportName, strOutput, parameters, data, null);
}
 
Example 18
Project: openlmis-stockmanagement   File: JasperReportService.java   View source code 6 votes vote down vote up
private String saveAndGetUrl(JasperReport report, String templateName) throws IOException {
  File reportTempFile;
  try {
    reportTempFile = createTempFile(templateName, ".jasper");
  } catch (IOException ex) {
    throw new JasperReportViewException(ERROR_JASPER_FILE_CREATION, ex);
  }

  try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
       ObjectOutputStream out = new ObjectOutputStream(bos)) {

    out.writeObject(report);
    writeByteArrayToFile(reportTempFile, bos.toByteArray());

    return reportTempFile.toURI().toURL().toString();
  }
}
 
Example 19
Project: jasperreports   File: SaveAction.java   View source code 6 votes vote down vote up
@Override
	public void performAction() 
	{
//		JasperDesign jasperDesign = getJasperDesign();
		JasperDesignCache cache = JasperDesignCache.getInstance(getJasperReportsContext(), getReportContext());
		Map<String, JasperDesignReportResource> cachedResources = cache.getCachedResources();
		for (String uri : cachedResources.keySet())
		{
			JasperDesignReportResource resource = cachedResources.get(uri);
			JasperDesign jasperDesign = resource.getJasperDesign();
			if (jasperDesign != null)
			{
				JasperReport jasperReport = resource.getReport();
				String appRealPath = null;//FIXMECONTEXT WebFileRepositoryService.getApplicationRealPath();
				try
				{
					JRSaver.saveObject(jasperReport, new File(new File(new File(appRealPath), "WEB-INF/repository"), uri));//FIXMEJIVE harcoded
				}
				catch (JRException e)
				{
					throw new JRRuntimeException(e);
				}
			}
		}
	}
 
Example 20
Project: jasperreports   File: JRSubreportExpressionFactory.java   View source code 6 votes vote down vote up
@Override
public Object createObject(Attributes atts)
{
	JRDesignExpression expression = new JRDesignExpression();

	String value = atts.getValue(JRXmlConstants.ATTRIBUTE_class);
	
	if (value != null)
	{
		// being backward compatible
		if(value.equals("dori.jasper.engine.JasperReport"))
		{
			value = JasperReport.class.getName();
		}
		expression.setValueClassName(value);
	}
	else
	{
		expression.setValueClass(java.lang.String.class);
	}

	return expression;
}
 
Example 21
Project: Java-Danfe   File: DanfeNfe.java   View source code 6 votes vote down vote up
private static void gerarDanfeNfse(String url, List<String> emit, List<String> dest, List<String> ser, List<String> nota, String xml, String logo) {
    try {
        // Teste
        //String compilado = System.getProperty("user.dir") + "/danfe_nfce_80.jasper";;
        String output = "danfe.pdf"; 
        map.put("emit", emit);
        map.put("dest", dest);
        map.put("ser", ser);
        map.put("nota", nota);
        map.put("logo", logo);
        // brasao
        String brasao = Paths.get(System.getProperty("user.dir"), "danfe","brasao.png").toAbsolutePath().toString();
        map.put("brasao", brasao);
        // JrDataSource
        JRDataSource jr = new JRXmlDataSource(xml);
        // Relatório compilado
        JasperReport report = (JasperReport) JRLoader.loadObjectFromFile(url);
        JasperPrint print = JasperFillManager.fillReport(report, map, jr);
        JasperExportManager.exportReportToPdfFile(print, output);
    } catch (JRException e) {
        System.out.println("erro: "+e.getMessage());
    }
}
 
Example 22
Project: jasperreports   File: JRFillCrosstab.java   View source code 6 votes vote down vote up
protected void loadEvaluator(JasperReport jasperReport)
{
	try
	{
		JREvaluator evaluator = JasperCompileManager.getInstance(filler.getJasperReportsContext()).getEvaluator(jasperReport, parentCrosstab);
		crosstabEvaluator = new JRCrosstabExpressionEvaluator(evaluator);
	}
	catch (JRException e)
	{
		throw 
			new JRRuntimeException(
				EXCEPTION_MESSAGE_KEY_EVALUATOR_LOADING_ERROR,
				(Object[])null,
				e);
	}
}
 
Example 23
Project: jasperreports   File: JRFiller.java   View source code 6 votes vote down vote up
/**
 * Fills a report.
 * <p/>
 * The data source used to fill the report is determined in the following way:
 * <ul>
 * 	<li>If a non-null value of the {@link net.sf.jasperreports.engine.JRParameter#REPORT_DATA_SOURCE REPORT_DATA_SOURCE}
 * has been specified, it will be used as data source.</li>
 * 	<li>Otherwise, if the report has a query then a data source will be created based on the query and connection
 * parameter values.</li>
 * 	<li>Otherwise, the report will be filled without a data source.</li>
 * </ul>
 * 
 * @param jasperReport the report
 * @param parameters the fill parameters
 * @return the filled report
 * @throws JRException
 */
public static JasperPrint fill(
	JasperReportsContext jasperReportsContext,
	JasperReport jasperReport, 
	Map<String,Object> parameters
	) throws JRException
{
	ReportFiller filler = createReportFiller(jasperReportsContext, jasperReport);

	try
	{
		JasperPrint jasperPrint = filler.fill(parameters);

		return jasperPrint;
	}
	catch (JRFillInterruptedException e)
	{
		throw 
			new JRException(
				EXCEPTION_MESSAGE_KEY_THREAD_INTERRUPTED,
				null,
				e);
	}
}
 
Example 24
Project: jasperreports   File: JRFiller.java   View source code 6 votes vote down vote up
protected static JRBaseFiller createBandReportFiller(JasperReportsContext jasperReportsContext, JasperReport jasperReport) throws JRException
{
	JRBaseFiller filler = null;

	switch (jasperReport.getPrintOrderValue())
	{
		case HORIZONTAL :
		{
			filler = new JRHorizontalFiller(jasperReportsContext, jasperReport);
			break;
		}
		case VERTICAL :
		{
			filler = new JRVerticalFiller(jasperReportsContext, jasperReport);
			break;
		}
	}
	return filler;
}
 
Example 25
Project: jasperreports   File: JRFiller.java   View source code 6 votes vote down vote up
public static ReportFiller createReportFiller(JasperReportsContext jasperReportsContext, JasperReport jasperReport) throws JRException
{
	ReportFiller filler;
	SectionTypeEnum sectionType = jasperReport.getSectionType();
	sectionType = sectionType == null ? SectionTypeEnum.BAND : sectionType;
	switch (sectionType)
	{
	case BAND:
		filler = createBandReportFiller(jasperReportsContext, jasperReport);
		break;
	case PART:
	{
		filler = new PartReportFiller(jasperReportsContext, jasperReport);
		break;
	}
	default:
		throw 
			new JRRuntimeException(
				EXCEPTION_MESSAGE_KEY_UNKNOWN_REPORT_SECTION_TYPE,  
				new Object[]{jasperReport.getSectionType()} 
				);
	}
	return filler;
}
 
Example 26
Project: java-swing-template   File: ReportsModel.java   View source code 5 votes vote down vote up
public static JasperPrint prepareReport(String reportpath) throws Exception {
    HashMap<String, Object> params = new HashMap<>();
    File f = new File("reports");
    String SUBREPORT_DIR = f.getAbsolutePath() + "\\";
    params.put("SUBREPORT_DIR", SUBREPORT_DIR);
    JasperReport jr = JasperCompileManager.compileReport(reportpath);
    return JasperFillManager.fillReport(jr, params, con);
}
 
Example 27
Project: Proyecto2017Seguros   File: ReporteMenu.java   View source code 5 votes vote down vote up
@Action(semantics = SemanticsOf.SAFE)
   @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
   @MemberOrder(sequence = "3")
public Blob imprimirClientesActivos() throws JRException, IOException {
	
	ClientesActivosDataSource datasource = new ClientesActivosDataSource();
	
	for (Cliente cli : clientesRepository.listarActivos()){
	
		ClientesActivosReporte reporteClientesActivos=new ClientesActivosReporte();
		
		reporteClientesActivos.setClienteNombre(cli.getClienteNombre());
		reporteClientesActivos.setClienteApellido(cli.getClienteApellido());
		reporteClientesActivos.setClienteDni(cli.getClienteDni());
		reporteClientesActivos.setClienteTipoDocumento(cli.getClienteTipoDocumento().toString());
		reporteClientesActivos.setPersonaMail(cli.getPersonaMail());
		reporteClientesActivos.setPersonaTelefono(cli.getPersonaTelefono());
		
		datasource.addParticipante(reporteClientesActivos);
	}
	String jrxml = "ClientesActivos.jrxml";
	String nombreArchivo = "Listado Clientes Activos ";
	
	InputStream input = ReporteRepository.class.getResourceAsStream(jrxml);
	JasperDesign jd = JRXmlLoader.load(input);
	
	JasperReport reporte = JasperCompileManager.compileReport(jd);
	Map<String, Object> parametros = new HashMap<String, Object>();
	JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, datasource);
	
	return ReporteRepository.imprimirReporteLista(jasperPrint, jrxml, nombreArchivo);
	
}
 
Example 28
Project: Proyecto2017Seguros   File: ReporteMenu.java   View source code 5 votes vote down vote up
@Action(semantics = SemanticsOf.SAFE)
   @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
   @MemberOrder(sequence = "5")
public Blob imprimirFacturacionAnualPorCompania() throws JRException, IOException {
   	
   	FacturacionDataSource datasource = new FacturacionDataSource();
	
	for (FacturacionCompaniasViewModel fac : facturacionRepository.facturacion()){
	
		FacturacionReporte facturacionCompania =new FacturacionReporte();
		
		facturacionCompania.setCompania(fac.getCompania().getCompaniaNombre().toString());
		facturacionCompania.setPrimaTotal(fac.getPrimaTotal());
		
		datasource.addParticipante(facturacionCompania);
	}
	String jrxml = "FacturacionCompanias.jrxml";
	String nombreArchivo = "Facturacion companias ";
	
	InputStream input = ReporteRepository.class.getResourceAsStream(jrxml);
	JasperDesign jd = JRXmlLoader.load(input);
	
	JasperReport reporte = JasperCompileManager.compileReport(jd);
	Map<String, Object> parametros = new HashMap<String, Object>();
	JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, datasource);
	
	return ReporteRepository.imprimirReporteLista(jasperPrint, jrxml, nombreArchivo);
   	
   }
 
Example 29
Project: Proyecto2017Seguros   File: ReporteMenu.java   View source code 5 votes vote down vote up
@Action(semantics = SemanticsOf.SAFE)
   @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
   @MemberOrder(sequence = "6")
public Blob imprimirPolizasPorCompania(
           @ParameterLayout(named="Compania: ") final Compania companiaSeleccionada) throws JRException, IOException {
   	
   	PolizaPorCompaniaDataSource datasource = new PolizaPorCompaniaDataSource();
	
	for (Poliza pol : polizaRepository.buscarPorCompania(companiaSeleccionada)){
	
		PolizaPorCompaniaReporte reportePolizaPorCompania =new PolizaPorCompaniaReporte();
		
		reportePolizaPorCompania.setPolizasCliente(pol.getPolizaCliente().toString());
		reportePolizaPorCompania.setPolizasCompania(pol.getPolizaCompania().getCompaniaNombre());
		reportePolizaPorCompania.setPolizaNumero(pol.getPolizaNumero());
		reportePolizaPorCompania.setPolizaFechaVigencia(pol.getPolizaFechaVigencia());
		reportePolizaPorCompania.setPolizaFechaVencimiento(pol.getPolizaFechaVencimiento());
		reportePolizaPorCompania.setPolizaFechaEmision(pol.getPolizaFechaEmision());
		reportePolizaPorCompania.setPolizaImporteTotal(pol.getPolizaImporteTotal());
		
		
		datasource.addParticipante(reportePolizaPorCompania);
	}
	String jrxml = "PolizasPorCompania.jrxml";
	String nombreArchivo = "Listado de polizas por compania"+" "+companiaSeleccionada.getCompaniaNombre()+" ";
	
	InputStream input = ReporteRepository.class.getResourceAsStream(jrxml);
	JasperDesign jd = JRXmlLoader.load(input);
	
	JasperReport reporte = JasperCompileManager.compileReport(jd);
	Map<String, Object> parametros = new HashMap<String, Object>();
	parametros.put("compania", companiaSeleccionada.getCompaniaNombre());
	JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, datasource);
	
	return ReporteRepository.imprimirReporteLista(jasperPrint, jrxml, nombreArchivo);
   }
 
Example 30
Project: Automekanik   File: ShikoKonsumatoret.java   View source code 5 votes vote down vote up
private void raporti(){
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                JasperReport jreport = JasperCompileManager.compileReport(raporti);
                JasperPrint jprint = JasperFillManager.fillReport(jreport, new HashedMap(), conn);
                JasperViewer.viewReport(jprint, false);
                conn.close();
            }catch (Exception ex){ex.printStackTrace();}
        }
    });
    btnRaport.setOnAction(e -> t.start());
}
 
Example 31
Project: Automekanik   File: ShikoPunetoret.java   View source code 5 votes vote down vote up
private void raporti(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                JasperReport jreport = JasperCompileManager.compileReport(raporti);
                JasperPrint jprint = JasperFillManager.fillReport(jreport, new HashMap(), conn);
                JasperViewer.viewReport(jprint, false);
                conn.close();
            }catch (Exception ex){ex.printStackTrace();}
        }
    }).start();
}
 
Example 32
Project: jasperreports   File: PartReportFiller.java   View source code 5 votes vote down vote up
public PartReportFiller(JasperReportsContext jasperReportsContext, JasperReport jasperReport, 
		PartFillerParent parent) throws JRException
{
	super(jasperReportsContext, jasperReport, parent);
	
	detailParts = new FillParts(jasperReport.getDetailSection(), factory);
	
	JRGroup[] reportGroups = jasperReport.getGroups();
	if (reportGroups == null || reportGroups.length == 0)
	{
		groupParts = Collections.emptyList();
		groupPartsByName = Collections.emptyMap();
	}
	else
	{
		groupParts = new ArrayList<GroupFillParts>(reportGroups.length);
		groupPartsByName = new HashMap<String, GroupFillParts>();
		for (JRGroup reportGroup : reportGroups)
		{
			GroupFillParts groupFillParts = new GroupFillParts(reportGroup, factory);
			groupParts.add(groupFillParts);
			groupPartsByName.put(reportGroup.getName(), groupFillParts);
		}
	}
	
	initDatasets();
	
	reportEvaluatedParts = new ArrayList<DelayedPrintPart>();
	
	if (parent == null)
	{
		JasperPrintPartOutput jasperPrintOutput = new JasperPrintPartOutput();
		partQueue = new FillPrintPartQueue(jasperPrintOutput);
	}
	else
	{
		partQueue = parent.getFiller().partQueue;
	}
}
 
Example 33
Project: Spring-MVC-Blueprints   File: AdminJasperReport.java   View source code 5 votes vote down vote up
private JasperReport getCompiledFile(String fileName,
		HttpServletRequest request) throws JRException {
	// Note: Always compile XML template
	JasperReport jasperReport = (JasperReport) JRLoader.loadObject(this
			.getClass().getClassLoader()
			.getResourceAsStream("config/JRUsers.jasper"));
	return jasperReport;
}
 
Example 34
Project: jasperreports   File: MaxPagesGovernor.java   View source code 5 votes vote down vote up
@Override
public void afterPageInit() throws JRScriptletException
{
	// cannot use PAGE_NUMBER variable because of timing issues and because of isResetPageNumber flag
	pages++;
	if (maxPages < pages)
	{
		throw 
			new MaxPagesGovernorException(
				((JasperReport)getParameterValue(JRParameter.JASPER_REPORT, false)).getName(),
				maxPages
				);
	}
}
 
Example 35
Project: spring4-understanding   File: AbstractJasperReportsView.java   View source code 5 votes vote down vote up
/**
 * Create a report using the given provider.
 * @param provider the JRDataSourceProvider to use
 * @return the created report
 */
protected JRDataSource createReport(JRDataSourceProvider provider) {
	try {
		JasperReport report = getReport();
		if (report == null) {
			throw new IllegalStateException("No main report defined for JRDataSourceProvider - " +
					"specify a 'url' on this view or override 'getReport()'");
		}
		return provider.create(report);
	}
	catch (JRException ex) {
		throw new IllegalArgumentException("Supplied JRDataSourceProvider is invalid", ex);
	}
}
 
Example 36
Project: jasperreports   File: RepositoryUtil.java   View source code 5 votes vote down vote up
/**
 *
 */
public JasperReport getReport(ReportContext reportContext, String location) throws JRException 
{
	JasperReport jasperReport = null;
	
	JasperDesignCache cache = JasperDesignCache.getInstance(jasperReportsContext, reportContext);
	if (cache != null)
	{
		jasperReport = cache.getJasperReport(location);
	}

	if (jasperReport == null)
	{
		ReportResource resource = getResourceFromLocation(location, ReportResource.class);
		if (resource == null)
		{
			throw 
				new JRException(
					EXCEPTION_MESSAGE_KEY_REPORT_NOT_FOUND,
					new Object[]{location});
		}

		jasperReport = resource.getReport();

		if (cache != null)
		{
			cache.set(location, jasperReport);
		}
	}

	return jasperReport;
}
 
Example 37
Project: jasperreports   File: JasperDesignCache.java   View source code 5 votes vote down vote up
/**
 * 
 */
public void set(String uri, JasperReport jasperReport)
{
	JasperDesignReportResource resource = new JasperDesignReportResource();
	resource.setReport(jasperReport);
	cachedResourcesMap.put(uri, resource);
}
 
Example 38
Project: ESIPC   File: Menu.java   View source code 5 votes vote down vote up
private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem13ActionPerformed
    // TODO add your handling code here:
    try {
        conectar cc= new conectar();
        
        JasperReport reportes=JasperCompileManager.compileReport("Factura.jrxml");
        JasperPrint print=JasperFillManager.fillReport(reportes, null, cc.conexion());
        JasperViewer.viewReport(print);
        
    } catch (Exception e) {
        System.out.printf(e.getMessage());
    }
  
}
 
Example 39
Project: ESIPC   File: Menu.java   View source code 5 votes vote down vote up
private void jMenuItem15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem15ActionPerformed
    // TODO add your handling code here:
    try {
        conectar cc= new conectar();
        
        JasperReport reportes=JasperCompileManager.compileReport("Nota.jrxml");
        JasperPrint print=JasperFillManager.fillReport(reportes, null, cc.conexion());
        JasperViewer.viewReport(print);
        
    } catch (Exception e) {
        System.out.printf(e.getMessage());
    }
}
 
Example 40
Project: ESIPC   File: Menu.java   View source code 5 votes vote down vote up
private void jMenuItem18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem18ActionPerformed
    // TODO add your handling code here:
     try {
        conectar cc= new conectar();
        
        JasperReport reportes=JasperCompileManager.compileReport("Departamento.jrxml");
        JasperPrint print=JasperFillManager.fillReport(reportes, null, cc.conexion());
        JasperViewer.viewReport(print);
        
    } catch (Exception e) {
        System.out.printf(e.getMessage());
    }
}