Jasperreports report with multiple parameters

Asked

Viewed 329 times

0

I have a report on JasperReports, is working properly. However, from the way it is, step only one meter each tipofrom the jsf page to the report, the screen is as per the image:

inserir a descrição da imagem aqui

What I need now is to be able to send more than one cliente , for example, for the report as a parameter. I haven’t been able to do it yet. A basic idea would be to have a button next to the combo, which when clicked would send the contents of this to a list, something like this and then this list of parameters sent to the report. But I couldn’t implement it, so if anyone can help, thank you.

Bean:

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.hibernate.Session;

import com.rodrigo.controleacidentes.model.Cliente;
import com.rodrigo.controleacidentes.model.StatusEntrada;
import com.rodrigo.controleacidentes.util.jsf.FacesUtil;
import com.rodrigo.controleacidentes.util.report.ExecutorRelatorioPdf;
import com.rodrigo.controleacidentes.util.report.ExecutorRelatorioXls;

@Named
@RequestScoped
public class RelatorioEntradasBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Date dataInicio;
    private Date dataFim;
    private Cliente cliente;
    private StatusEntrada statusEntrada;

    public StatusEntrada getStatusEntrada() {
        return statusEntrada;
    }

    public void setStatusEntrada(StatusEntrada statusEntrada) {
        this.statusEntrada = statusEntrada;
    }

    public void teste(StatusEntrada st) {
        // StatusEntrada entrada = StatusEntrada.valueOf(st);
        System.out.println("TESTE: " + st);
    }

    @Inject
    private FacesContext facesContext;

    @Inject
    private HttpServletResponse response;

    @Inject
    private EntityManager manager;

    public void emitirXls() {
        Map<String, Object> parametros = new HashMap<>();
        parametros.put("data_inicio", this.dataInicio);
        parametros.put("data_fim", this.dataFim);
        if (cliente != null) {

            System.out.println("TESTE: " + cliente.getNome());
            parametros.put("nome_cliente", cliente.getNome());
        }
        if (statusEntrada != null) {
            System.out.println("TESTE :" + statusEntrada.getDescricao());
            parametros.put("status_entrada", statusEntrada.getDescricao());

        }

        ExecutorRelatorioXls executor = new ExecutorRelatorioXls("/relatorios/RelatorioEntradasNome.jasper",
                this.response, parametros, "Relatório Entradas.xls");

        Session session = manager.unwrap(Session.class);
        session.doWork(executor);

        if (executor.isRelatorioGerado()) {
            facesContext.responseComplete();
        } else {
            FacesUtil.addErrorMessage("A execução do relatório não retornou dados.");
        }
    }

    public void emitirPdf() {
        Map<String, Object> parametros = new HashMap<>();
        parametros.put("data_inicio", this.dataInicio);
        parametros.put("data_fim", this.dataFim);
        parametros.put("nome_cliente", this.cliente);

        ExecutorRelatorioPdf executor = new ExecutorRelatorioPdf("/relatorios/RelatorioEntradasNome.jasper",
                this.response, parametros, "Relatório Entradas.pdf");

        Session session = manager.unwrap(Session.class);
        session.doWork(executor);

        if (executor.isRelatorioGerado()) {
            facesContext.responseComplete();
        } else {
            FacesUtil.addErrorMessage("A execução do relatório não retornou dados.");
        }
    }

    @NotNull
    public Date getDataInicio() {
        return dataInicio;
    }

    public void setDataInicio(Date dataInicio) {
        this.dataInicio = dataInicio;
    }

    @NotNull
    public Date getDataFim() {
        return dataFim;
    }

    public void setDataFim(Date dataFim) {
        this.dataFim = dataFim;
    }

    @NotNull
    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

}

Executioner:

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.hibernate.jdbc.Work;

import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

public class ExecutorRelatorioXls implements Work {

    private String caminhoRelatorio;
    private HttpServletResponse response;
    private Map<String, Object> parametros;
    private String nomeArquivoSaida;

    private boolean relatorioGerado;

    public ExecutorRelatorioXls(String caminhoRelatorio, HttpServletResponse response, Map<String, Object> parametros,
            String nomeArquivoSaida) {
        this.caminhoRelatorio = caminhoRelatorio;
        this.response = response;
        this.parametros = parametros;
        this.nomeArquivoSaida = nomeArquivoSaida;

        this.parametros.put(JRParameter.REPORT_LOCALE, new Locale("pt", "BR"));
    }

    @Override
    public void execute(Connection connection) throws SQLException {
        try {
            InputStream relatorioStream = this.getClass().getResourceAsStream(this.caminhoRelatorio);

            JasperPrint print = JasperFillManager.fillReport(relatorioStream, this.parametros, connection);
            this.relatorioGerado = print.getPages().size() > 0;

            if (this.relatorioGerado) {
                JRXlsExporter exportador = new JRXlsExporter();
                exportador.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
                exportador.setParameter(JRXlsExporterParameter.JASPER_PRINT, print);

                exportador.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
                exportador.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
                exportador.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);

                response.setHeader("Content-Transfer-Encoding", "Cp1256");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + this.nomeArquivoSaida + "\"");

                exportador.exportReport();
            }
        } catch (Exception e) {
            throw new SQLException("Erro ao executar relatório " + this.caminhoRelatorio, e);
        }
    }

    public boolean isRelatorioGerado() {
        return relatorioGerado;
    }

}

Query in the report:

SELECT DISTINCT
     ocorrencia.`id` AS ocorrencia_id,
     ocorrencia.`descricao` AS ocorrencia_descricao,
     ocorrencia.`condicao_tempo` AS ocorrencia_condicao_tempo,
     ocorrencia.`data_ocorrencia` AS ocorrencia_data_ocorrencia,
     ocorrencia.`periodo_ocorrencia` AS ocorrencia_periodo_ocorrencia,
     ocorrencia.`condutor_id` AS ocorrencia_condutor_id,
     condutor.`id` AS condutor_id,
     condutor.`codigo` AS condutor_codigo,
     condutor.`nome` AS condutor_nome,
     entrada_acidente.`id` AS entrada_acidente_id,
     entrada_acidente.`data_criacao` AS entrada_acidente_data_criacao,
     entrada_acidente.`ocorrencia_id` AS entrada_acidente_ocorrencia_id,
     entrada_acidente.`valor_unitario` AS entrada_acidente_valor_unitario,
     cliente.`id` AS cliente_id,
     cliente.`nome` AS cliente_nome,
     entrada_acidente.`status` AS entrada_acidente_status
FROM
     `condutor` condutor INNER JOIN `ocorrencia` ocorrencia ON condutor.`id` = ocorrencia.`condutor_id`
     INNER JOIN `entrada_acidente` entrada_acidente ON ocorrencia.`id` = entrada_acidente.`ocorrencia_id`
     INNER JOIN `cliente` cliente ON entrada_acidente.`cliente_id` = cliente.`id`
WHERE
     entrada_acidente.`data_criacao` BETWEEN $P{data_inicio} AND $P{data_fim}
 AND cliente.`nome` = $P{nome_cliente}
 AND entrada_acidente.`status` = $P{status_entrada}

xhtml:

<ui:composition template="/WEB-INF/template/LayoutPadrao.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

    <ui:define name="titulo">Relatório de entradas emitidas</ui:define>

    <ui:define name="corpo">
        <h:form id="frm">
            <h1>Relatório de entradas emitidas</h1>

            <p:messages autoUpdate="true" closable="true" />

            <p:toolbar style="margin-top: 20px">
                <p:toolbarGroup>
                    <p:commandButton value="EmitirPdf"
                        action="#{relatorioEntradasBean.emitirPdf}" ajax="false" />
                    <p:commandButton value="EmitirXls"
                        action="#{relatorioEntradasBean.emitirXls}" ajax="false" />
                </p:toolbarGroup>
            </p:toolbar>

            <p:panelGrid columns="7" id="painel"
                style="width: 100%; margin-top: 20px" columnClasses="rotulo, campo">
                <p:outputLabel value="Data de criação" />
                <h:panelGroup>
                    <p:calendar value="#{relatorioEntradasBean.dataInicio}"
                        label="Data inicial" pattern="dd/MM/yyyy" size="8" />
                    <p:spacer width="8" />
                    <h:outputText value="a" />
                    <p:spacer width="8" />
                    <p:calendar value="#{relatorioEntradasBean.dataFim}"
                        label="Data final" pattern="dd/MM/yyyy" size="8" />
                </h:panelGroup>
                <h:panelGroup>
                    <p:outputLabel value="Cliente" for="cliente" />
                    <p:autoComplete id="cliente" size="40" dropdown="true"
                        value="#{relatorioEntradasBean.cliente}"
                        completeMethod="#{cadastroEntradaBean.completarCliente}"
                        var="cliente" itemLabel="#{cliente.nome}" itemValue="#{cliente}"
                        forceSelection="true" />
                </h:panelGroup>


                <p:outputLabel value="Status" />
                <h:panelGroup>
                    <p:selectOneMenu id="statusEntrada"
                        value="#{relatorioEntradasBean.statusEntrada}">
                        <f:selectItem itemLabel="Selecione" />
                        <f:selectItems value="#{enumProviderStatus.statusEntradas}"
                            var="statusEntrada" itemValue="#{statusEntrada}"
                            itemLabel="#{statusEntrada.descricao}" />
                    </p:selectOneMenu>
                </h:panelGroup>
            </p:panelGrid>
        </h:form>
    </ui:define>
</ui:composition>

Update1:

     //query "base"
    public String getQueryPrincipal(String queryPrincipal) {
        return queryPrincipal = "SELECT  cliente.id AS cliente_id,"
                + " cliente.doc_receita_federal AS cliente_doc_receita_federal," + "  cliente.email AS cliente_email,"
                + " cliente.nome AS cliente_nome," + "  cliente.tipo AS cliente_tipo," + "  condutor.id AS condutor_id,"
                + " condutor.codigo AS condutor_codigo," + "  condutor.nome AS condutor_nome,"
                + " despesa.id AS despesa_id," + " despesa.nome AS despesa_nome," + "   despesa.sku AS despesa_sku,"
                + " despesa.categoria_id AS despesa_categoria_id," + "  entrada_acidente.id AS entrada_acidente_id,"
                + " entrada_acidente.attach AS entrada_acidente_attach,"
                + " entrada_acidente.data_criacao AS entrada_acidente_data_criacao,"
                + " entrada_acidente.fileName AS entrada_acidente_fileName,"
                + " entrada_acidente.forma_pagamento AS entrada_acidente_forma_pagamento,"
                + " entrada_acidente.observacao AS entrada_acidente_observacao,"
                + " entrada_acidente.status AS entrada_acidente_status,"
                + " entrada_acidente.valor_desconto AS entrada_acidente_valor_desconto,"
                + " entrada_acidente.valor_total AS entrada_acidente_valor_total,"
                + " entrada_acidente.cliente_id AS entrada_acidente_cliente_id,"
                + " entrada_acidente.ocorrencia_id AS entrada_acidente_ocorrencia_id,"
                + " entrada_acidente.vendedor_id AS entrada_acidente_vendedor_id,"
                + " entrada_acidente.valor_unitario AS entrada_acidente_valor_unitario,"
                + " entrada_acidente.quantidade AS entrada_acidente_quantidade,"
                + " item_despesa.id AS item_despesa_id," + "  item_despesa.quantidade AS item_despesa_quantidade,"
                + " item_despesa.valor_unitario AS item_despesa_valor_unitario,"
                + " item_despesa.produto_id AS item_despesa_produto_id,"
                + " item_despesa.pedido_id AS item_despesa_pedido_id," + " ocorrencia.id AS ocorrencia_id,"
                + " ocorrencia.descricao AS ocorrencia_descricao,"
                + " ocorrencia.condicao_tempo AS ocorrencia_condicao_tempo,"
                + " ocorrencia.data_ocorrencia AS ocorrencia_data_ocorrencia,"
                + " ocorrencia.numero_vitimas AS ocorrencia_numero_vitimas,"
                + " ocorrencia.periodo_ocorrencia AS ocorrencia_periodo_ocorrencia" + " FROM "
                + " cliente cliente INNER JOIN entrada_acidente entrada_acidente ON cliente.id = entrada_acidente.cliente_id"
                + " INNER JOIN item_despesa item_despesa ON entrada_acidente.id = item_despesa.pedido_id"
                + " INNER JOIN ocorrencia ocorrencia ON entrada_acidente.ocorrencia_id = ocorrencia.id"
                + " INNER JOIN condutor condutor ON ocorrencia.condutor_id = condutor.id"
                + " INNER JOIN despesa despesa ON item_despesa.produto_id = despesa.id";
    }

query adding the "Where data"

     public String getData(String dataI, String dataF) {
        return dataParaQuery = " where  entrada_acidente.data_criacao between '" + dataI + "'" + "and '" + dataF + "' "
                + "";
    }   

Method generating the report:

public void execute() throws ParseException {
        JasperReportBuilder report = DynamicReports.report();
        configure(report);
        convert();
        report.setDataSource(getQueryPrincipal(queryPrincipal) + getData(dataI, dataF), con);

        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        try {
            response.setContentType("application/pdf");
            report.toPdf(response.getOutputStream());
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

xhtml (updated update2):

<ui:composition template="/WEB-INF/template/LayoutPadrao.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">


<ui:define name="titulo">Relatório de entradas emitidas</ui:define>

<ui:define name="corpo">
    <h:form id="frm" acceptcharset="ISO-8859-1" >
        <h1>Relatório de entradas emitidas</h1>

        <p:messages autoUpdate="true" closable="true" />

        <p:toolbar style="margin-top: 20px">
            <p:toolbarGroup>
                <p:commandButton value="EmitirPdf"
                    action="#{relatorioEntradasBean.emitirPdf}" ajax="false" />
                <p:commandButton value="EmitirXls"
                    action="#{relatorioEntradasBean.emitirXls}" ajax="false" />
            </p:toolbarGroup>
            <p:toolbarGroup>
                <h:commandButton action="#{simpleReport.execute}" value="show pdf" />
            </p:toolbarGroup>
            <p:toolbarGroup>
                <h:commandLink value="Click here"
                    action="#{simpleReport.addtoList(nome)}">
                    <f:setPropertyActionListener target="#{simpleReport.nome}"
                        value="nome" />
                </h:commandLink>
            </p:toolbarGroup>
            <p:toolbarGroup>
                <h:inputText id="nome" value="#{simpleReport.nome}" />
            </p:toolbarGroup>

            <p:toolbarGroup>
                <h:inputText binding="#{nome}" />
                <h:commandButton value="Test"
                    action="#{simpleReport.addtoList(nome.value)}" />
            </p:toolbarGroup>

        </p:toolbar>

        <p:panelGrid columns="7" id="painel"
            style="width: 100%; margin-top: 20px" columnClasses="rotulo, campo">
            <p:outputLabel value="Data de criação" />
            <h:panelGroup>
                <p:calendar value="#{simpleReport.dataInicialQuery}"
                    label="Data inicial" pattern="dd/MM/yyyy" size="8" />
                <p:spacer width="8" />
                <h:outputText value="a" />
                <p:spacer width="8" />
                <p:calendar value="#{simpleReport.dataFinalQuery}"
                    label="Data final" pattern="dd/MM/yyyy" size="8" />
            </h:panelGroup>
            <h:panelGroup>
                <p:outputLabel value="Cliente" for="cliente" />
                <p:autoComplete id="cliente" size="40" dropdown="true"
                    value="#{simpleReport.cliente}"
                    completeMethod="#{simpleReport.completarCliente}" var="cliente"
                    itemLabel="#{cliente.nome}" itemValue="#{cliente}"
                    forceSelection="true" />
            </h:panelGroup>


            <p:outputLabel value="Status" />
            <h:panelGroup>
                <p:selectOneMenu id="statusEntrada"
                    value="#{relatorioEntradasBean.statusEntrada}">
                    <f:selectItem itemLabel="Selecione" />
                    <f:selectItems value="#{enumProviderStatus.statusEntradas}"
                        var="statusEntrada" itemValue="#{statusEntrada}"
                        itemLabel="#{statusEntrada.descricao}" />
                </p:selectOneMenu>
            </h:panelGroup>
        </p:panelGrid>
    </h:form>
</ui:define>

Update2 methods to receive and concatenate the names coming from the jsf page:

private ArrayList<String> test = new ArrayList<String>();

public void addtoList(String nome) {
        test.add(nome);
    }

    public String nomesParaQuery(String queryNome) {

        StringBuilder sb = new StringBuilder("and cliente.nome IN (");
        boolean added = false;
        for (String s : test) {
            if (added) {
                sb.append(",");
            }
            sb.append("'");
            sb.append(s);
            sb.append("'");
            added = true;
        }
        sb.append(")");
        queryNome = sb.toString();
        return queryNome;
    }

Method generating the report:

public void execute() throws ParseException {
        JasperReportBuilder report = DynamicReports.report();
        configure(report);
        convert();
        report.setDataSource(getQueryPrincipal(queryPrincipal) + getData(dataI, dataF) + nomesParaQuery(queryNome),
                con);
                ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        try {
            response.setContentType("application/pdf");
            report.toPdf(response.getOutputStream());
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

clienteConvert:

package com.rodrigo.controleacidentes.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import com.rodrigo.controleacidentes.model.Cliente;
import com.rodrigo.controleacidentes.repository.Clientes;
import com.rodrigo.controleacidentes.util.cdi.CDIServiceLocator;

@FacesConverter(forClass=Cliente.class)
public class ClienteConverter implements Converter {

    //@Inject
    private Clientes clientes;

    public ClienteConverter() {
        this.clientes = (Clientes) CDIServiceLocator.getBean(Clientes.class);
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        Cliente retorno = null;

        if (value != null) {
            retorno = this.clientes.porId(new Long(value));
        }

        return retorno;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null) {
            Cliente cliente = (Cliente) value;
            return cliente.getId() == null ? null : cliente.getId().toString();
        }
        return "";
    }

}

simpleReport:

@Named
@ViewScoped
public class SimpleReport implements Serializable {

    private static final long serialVersionUID = 1L;
    Date date = null;
    Connection con = new SQLConnection().getConnection();
    String dataInicialQuery;
    String dataFinalQuery;
    String queryPrincipal = "";
    String dataI = "";
    String dataF = "";
    private Cliente cliente;
    String dataParaQuery = "";
    String queryNome = "";
    private ArrayList<String> test = new ArrayList<String>();
    String queryConcatenadaNome = "";
    private String nome = "";
    @Inject
    private Clientes clientes;

    public void addCliente(SelectEvent event) {
        String value = (String) event.getObject();
        System.out.println("selected " + value);

System.out.println("classe: " + event.getObject().getClass().toString());

    }

    public void addtoList(String cliente) {
        test.add(cliente);
        System.out.println(cliente);
    }

    public String nomesParaQuery(String queryNome) {

        StringBuilder sb = new StringBuilder("and cliente.id IN (");
        boolean added = false;
        for (String s : test) {
            if (added) {
                sb.append(",");
            }
            sb.append("'");
            sb.append(s);
            sb.append("'");
            added = true;
        }
        sb.append(")");
        queryNome = sb.toString();
        return queryNome;
    }

    public String getData(String dataI, String dataF) {
        return dataParaQuery = " where  entrada_acidente.data_criacao between '" + dataI + "'" + "and '" + dataF + "' "
                + "";
    }

    public String getQueryPrincipal(String queryPrincipal) {
        return queryPrincipal = "SELECT  cliente.id AS cliente_id,"
                + " cliente.doc_receita_federal AS cliente_doc_receita_federal," + "  cliente.email AS cliente_email,"
                + " cliente.nome AS cliente_nome," + "  cliente.tipo AS cliente_tipo," + "  condutor.id AS condutor_id,"
                + " condutor.codigo AS condutor_codigo," + "  condutor.nome AS condutor_nome,"
                + " despesa.id AS despesa_id," + " despesa.nome AS despesa_nome," + "   despesa.sku AS despesa_sku,"
                + " despesa.categoria_id AS despesa_categoria_id," + "  entrada_acidente.id AS entrada_acidente_id,"
                + " entrada_acidente.attach AS entrada_acidente_attach,"
                + " entrada_acidente.data_criacao AS entrada_acidente_data_criacao,"
                + " entrada_acidente.fileName AS entrada_acidente_fileName,"
                + " entrada_acidente.forma_pagamento AS entrada_acidente_forma_pagamento,"
                + " entrada_acidente.observacao AS entrada_acidente_observacao,"
                + " entrada_acidente.status AS entrada_acidente_status,"
                + " entrada_acidente.valor_desconto AS entrada_acidente_valor_desconto,"
                + " entrada_acidente.valor_total AS entrada_acidente_valor_total,"
                + " entrada_acidente.cliente_id AS entrada_acidente_cliente_id,"
                + " entrada_acidente.ocorrencia_id AS entrada_acidente_ocorrencia_id,"
                + " entrada_acidente.vendedor_id AS entrada_acidente_vendedor_id,"
                + " entrada_acidente.valor_unitario AS entrada_acidente_valor_unitario,"
                + " entrada_acidente.quantidade AS entrada_acidente_quantidade,"
                + " item_despesa.id AS item_despesa_id," + "  item_despesa.quantidade AS item_despesa_quantidade,"
                + " item_despesa.valor_unitario AS item_despesa_valor_unitario,"
                + " item_despesa.produto_id AS item_despesa_produto_id,"
                + " item_despesa.pedido_id AS item_despesa_pedido_id," + " ocorrencia.id AS ocorrencia_id,"
                + " ocorrencia.descricao AS ocorrencia_descricao,"
                + " ocorrencia.condicao_tempo AS ocorrencia_condicao_tempo,"
                + " ocorrencia.data_ocorrencia AS ocorrencia_data_ocorrencia,"
                + " ocorrencia.numero_vitimas AS ocorrencia_numero_vitimas,"
                + " ocorrencia.periodo_ocorrencia AS ocorrencia_periodo_ocorrencia" + " FROM "
                + " cliente cliente INNER JOIN entrada_acidente entrada_acidente ON cliente.id = entrada_acidente.cliente_id"
                + " INNER JOIN item_despesa item_despesa ON entrada_acidente.id = item_despesa.pedido_id"
                + " INNER JOIN ocorrencia ocorrencia ON entrada_acidente.ocorrencia_id = ocorrencia.id"
                + " INNER JOIN condutor condutor ON ocorrencia.condutor_id = condutor.id"
                + " INNER JOIN despesa despesa ON item_despesa.produto_id = despesa.id";
    }

    public void convert() throws ParseException {

        SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
        df.setTimeZone(TimeZone.getTimeZone("BRT"));
        DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        Date dInicial = df.parse(dataInicialQuery);
        Date dFinal = df.parse(dataFinalQuery);
        System.out.println("DateD: " + dInicial);
        String dataInicialUTC = utcFormat.format(dInicial);
        String dataFinalUTC = utcFormat.format(dFinal);
        System.out.println("dataInicialUTC:" + (dataInicialUTC));
        System.out.println("dataFinalUTC:" + (dataFinalUTC));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        dataI = sdf.format(dInicial);
        dataF = sdf.format(dFinal);
        System.out.println("New Date:" + (dataI));
        System.out.println("New Date:" + (dataF));

    }

    private void configure(JasperReportBuilder report) {
        report.setTemplate(Template.reportTemplate)
                .columns(
                        col.column("Cliente", "cliente_nome", type.stringType())
                                .setHorizontalAlignment(HorizontalAlignment.CENTER),
                        col.column("Status", "entrada_acidente_status", type.stringType())
                                .setHorizontalAlignment(HorizontalAlignment.CENTER),
                        col.column("Valor", "entrada_acidente_valor_unitario", type.bigDecimalType())
                                .setHorizontalAlignment(HorizontalAlignment.CENTER))
                .title(Template.createTitleComponent("Relatório")).pageFooter(Template.footerComponent);
    }

    public void execute() throws ParseException {
        JasperReportBuilder report = DynamicReports.report();
        configure(report);
        convert();
        report.setDataSource(getQueryPrincipal(queryPrincipal) + getData(dataI, dataF) + nomesParaQuery(queryNome),
                con);
        System.out.println("Name:" + nome);
        System.out.println(
                "QQQ:" + getQueryPrincipal(queryPrincipal) + getData(dataI, dataF) + nomesParaQuery(queryNome));
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        try {
            response.setContentType("application/pdf");
            report.toPdf(response.getOutputStream());
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getDataInicialQuery() {
        return dataInicialQuery;
    }

    public void setDataInicialQuery(String dataInicialQuery) {
        this.dataInicialQuery = dataInicialQuery;
    }

    public String getDataFinalQuery() {
        return dataFinalQuery;
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public void setDataFinalQuery(String dataFinalQuery) {
        this.dataFinalQuery = dataFinalQuery;
    }

    public List<Cliente> completarCliente(String nome) {
        return this.clientes.porNome(nome);
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

1 answer

1


There are a few ways to do what you want in Jasper Reports:

1 - Continue using the query in the report and pass a list of clients as parameter

You today pass as parameters a map where you inform:

Map<String, Object> parametros = new HashMap<>();
parametros.put("data_inicio", this.dataInicio);
parametros.put("data_fim", this.dataFim);
parametros.put("nome_cliente", this.cliente);

The first solution consists of not only passing a client but a list of clients, for example their id in a String variable that will be replaced in your query, for example:

 Map<String, Object> parametros = new HashMap<>();
 parametros.put("clientes", "('1', '2', '3', '4')");

This string would be filled out dynamically is clear and in the report query you would modify to something like:

...
WHERE
     entrada_acidente.`data_criacao` BETWEEN $P{data_inicio} AND $P{data_fim}
 AND cliente.id IN $P{clientes}
 AND entrada_acidente.`status` = $P{status_entrada}
...


2 - Use a datasource instead of letting the report run the query

The idea of this approach would be to pass the datasource to the report using the method

fillReport(java.io.InputStream inputStream, java.util.Map<java.lang.String,java.lang.Object> parameters, JRDataSource dataSource) 

This date being of various types, a list of objects or even the result Set. To mount it would be as follows:

ResultSet rsRelatorio = dao.executaConsultaRelatorioClientes(); //apenas para ilustrar, aqui executa a consulta e retorna o resultSet.
JasperPrint print = JasperFillManager.fillReport(relatorioStream, this.parametros, connection, new JRResultSetDataSource(rsRelatorio));

In this approach you would also have to modify your query in a way that loads multiple clients.

There are other ways, but in all of them you should make a change to your query or data source so that you load the clients according to what you set.

  • I believe I understood, I will check, however, in the meantime when I asked the question, as I could not advance, I searched on the DynamicReports who also uses the JasperReports ( on a web project), as it had been used on desktop. In my opinion it is more "practical" at least in parts because it does not need jrxml, it sends everything from the java class, columns, parameters etc.... I will save your answer , and depending on the results in DynamicReports i return to this approach. Thanks for while.

  • I added the codes according to the new approach (Updade1), I think it has something to do with your second suggestion, could you take a look? Now I no longer have jrxml, and pass the required columns and data straight from the java class. The difficulty of putting this client list "in the query" remains. In addition to sending these clients from the jsf page.

  • @Rodrigo is a little difficult to understand his problem. I believe that it is even complicated to discuss here. I created a meeting room in the stack chat for this http://chat.stackexchange.com/rooms/46019/parametros-no-jasper-reports. I don’t think you ever accessed the chat because I couldn’t invite you. Access this link and comment here that I invite again.

  • I accessed the link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.