Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

Dúvida no Ex. 10 da Aula 2 - Melhorando a coesão de nossas classes

Olá, estou tentando colocar em prática os conhecimentos adquiridos no curso e gostaria da ajuda dos colegas. Tenho um sistema web, nesse sistema trabalho bastante com a geração de relatórios, downloads, uploads, ftp, exportação para xls etc, enfim faço bastante uso de IO. Após assistir a aula parei para repensar o design dos meus controladores e vi que alguns trechos de código se repetiam em vários locais, então resolvi desmembrar esses códigos em outras classes, mas a surgiu pois nessas classes desmembradas fico retornando Input Streams, posso ter problemas de lentidão ou excesso de consumo de banda ou tráfego de rede devido ao meu novo design? oque acham desse refactoring?

1- controler antigo com código repetido em ouros locais e com várias responsabilidades:

public class RemessaVM{

public void gerarRelatorioXLS() throws JRException{


        List<RemessaBean> remessasBean = new ArrayList<RemessaBean>();
        for(Remessa r: remessas){
        RemessaBean bean = new RemessaBean(r);
        remessasBean.add(bean);
        }
        String webapp = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
        String path = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/relatorios");

        Map parameters = new HashMap();
        parameters.put("logo", webapp+"imagens/logo_tcema_novo.gif");

        JRDataSource ds= new JRBeanCollectionDataSource(remessasBean);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JasperPrint jasperPrint = JasperFillManager.fillReport(path + "/remessa.jasper", parameters, ds);
        JRXlsExporter xlsExporter = new JRXlsExporter();
        xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);  
        xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM,baos);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS,Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);    
        xlsExporter.setParameter(JRXlsExporterParameter.PARAMETERS_OVERRIDE_REPORT_HINTS, Boolean.TRUE);    
        xlsExporter.exportReport();
        byte[] bytes= baos.toByteArray(); 
        final InputStream mediais = new ByteArrayInputStream(bytes);

        Filedownload.save(mediais,"application/vnd.ms-excel","remessas.xls");    
    }

    @SuppressWarnings("unchecked")
    public void gerarRelatorio() throws FileNotFoundException, JRException{    

        List<RemessaBean> remessasBean = new ArrayList<RemessaBean>();
        for(Remessa r: remessas){
        RemessaBean bean = new RemessaBean(r);
        remessasBean.add(bean);
        }
        String webapp = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
        String path = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/relatorios");
        InputStream is = new FileInputStream(path + "/remessas.jasper");
        Map parameters = new HashMap();
        parameters.put("logo", webapp+"imagens/logo_tcema_novo.gif");
        JRDataSource ds= new JRBeanCollectionDataSource(remessasBean);
        final byte[] buf = JasperRunManager.runReportToPdf(is, parameters,ds);
        final InputStream mediais = new ByteArrayInputStream(buf);
        final AMedia amedia = new AMedia("remessas.pdf", "pdf", "application/pdf", mediais);

        Map parameters = new HashMap();        
        report.setSrc("relatorios/remessas.jasper");
        String caminho = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
parameters.put("logo",caminho+"imagens/logo_novo.gif");
        report.setParameters(parameters);    
        report.setDatasource(createReportDataSource());
        report.setType("pdf");*/
        report.setContent(amedia);
        binder.loadComponent(report);
        winreport.setVisible(true);
        winreport.doHighlighted();

    }

}

2: após o refactory separei os códigos de geração dos arquivos:

public class RemessaVM{

@Command
    public void gerarRelatorio(){    

        try {
            List<RemessaBean> remessasBean = new ArrayList<RemessaBean>();
            for(Remessa r: remessas){
                RemessaBean bean = new RemessaBean(r);
                remessasBean.add(bean);
            }
            GeradorRelatorio geradorRelatorio = new GeradorRelatorio(remessasBean, "/remessa.jasper");
            final InputStream mediais = geradorRelatorio.gerar();
            final AMedia amedia = new AMedia("remessas.pdf", "pdf", "application/pdf", mediais);
            report.setContent(amedia);
            winReport.setVisible(true);
            winReport.doHighlighted();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Messagebox.show("Não foi possível localizar o arquivo base do relatório","FINGER",Messagebox.OK,Messagebox.ERROR);
        } catch (JRException e) {

            e.printStackTrace();
            Messagebox.show("Erro ao gerar relatório","FINGER",Messagebox.OK,Messagebox.ERROR);
        }

    }



    @Command
    public void gerarRelatorioXLS(){

        try {
            List<RemessaBean> remessasBean = new ArrayList<RemessaBean>();
            for(Remessa r: remessas){
                RemessaBean bean = new RemessaBean(r);
                remessasBean.add(bean);
            }
            ExportadorXLS exportador = new ExportadorXLS(remessasBean,"/remessa.jasper");
            final InputStream mediais = exportador.exportar();
            Filedownload.save(mediais,"application/vnd.ms-excel","remessas.xls");
        } catch (JRException e) {

            e.printStackTrace();
            Messagebox.show("Erro ao exportar","FINGER",Messagebox.OK,Messagebox.ERROR);

        }
    }
}

public class GeradorRelatorio {


    private Collection<?> lista;
    private String nomeArquivo;


    public  GeradorRelatorio(Collection<?> lista, String nomeArquivo) {
        super();
        this.lista = lista;
        this.nomeArquivo = nomeArquivo;
    }




    public InputStream gerar() throws FileNotFoundException, JRException{

        String webapp = ZKUtils.caminhoApp();
        String path = ZKUtils.caminhoRelatorios();
        InputStream is = new FileInputStream(path + nomeArquivo);
        Map <String, Object> parameters = new HashMap<String, Object>();
        parameters.put("logo", webapp+"imagens/logo_novo.gif");
        JRDataSource ds= new JRBeanCollectionDataSource(lista);
        final byte[] buf = JasperRunManager.runReportToPdf(is, parameters,ds);
        final InputStream mediais = new ByteArrayInputStream(buf);
        return mediais;

    }
}

public class ExportadorXLS {


    private Collection<?> lista;
    private String nomeArquivo;


    public ExportadorXLS(Collection<?> lista, String nomeArquivo) {
        super();
        this.lista = lista;
        this.nomeArquivo = nomeArquivo;
    }


    public InputStream exportar() throws JRException{


        String path = ZKUtils.caminhoRelatorios();
        Map <String, Object> parameters  = new HashMap<String, Object>();
        JRDataSource ds= new JRBeanCollectionDataSource(lista);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JasperPrint jasperPrint = JasperFillManager.fillReport(path +nomeArquivo, parameters, ds);
        JRXlsExporter xlsExporter = new JRXlsExporter();
        xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);  
        xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM,baos);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS,Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.TRUE);
        xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);    
        xlsExporter.setParameter(JRXlsExporterParameter.PARAMETERS_OVERRIDE_REPORT_HINTS, Boolean.TRUE);    
        xlsExporter.exportReport();
        byte[] bytes= baos.toByteArray(); 
        return new ByteArrayInputStream(bytes);
    }
}

consegui separar as responsabilidades, mas não sei se é boa ideia ficar retornando input stream pra ca e pra lá

3 respostas
solução!

Oi Ricardo,

Não vejo problemas em retornar InputStream em vários pontos do sistema.

Inclusive assim é até melhor, pois você não fica preso a uma implementação específica, como FileInputStream ou ByteArrayInputStream.

Bons estudos!

Tb acho que está bem ok esse novo código, Ricardo!

Fico feliz que tenha conseguido aplicar as ideias do curso no seu código do dia a dia!

Obrigado pelas respostas, o objetivo é esse mesmo aproveitar o curso ao máximo :)

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software