当前位置: 首页 > 知识库问答 >
问题:

我得到一个stackOverflow错误时,试图生成一个非常大的PDF文件在Java

武睿
2023-03-14

当生成PDF的数据很小时,生成的PDF没有问题,但当数据很大时,我得到StackOverflower错误。

16:40:37,510 WARN  [org.hibernate.engine.loading.internal.LoadContexts] (default task-54) HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@5df3d7ab<rs=oracle.jdbc.driver.OracleResultSetImpl@357156df>
16:40:37,510 WARN  [org.hibernate.engine.loading.internal.CollectionLoadContext] (default task-54) HHH000160: On CollectionLoadContext#cleanup, localLoadingCollectionKeys contained [1] entries
16:40:37,528 ERROR [br.gov.ans.commons.rest.exception.handler.ExceptionHandler] (default task-54) org.modelmapper.MappingException: ModelMapper mapping errors:

1) Error mapping br.gov.ans.rps.rede.services.entities.Movimentacao to br.gov.ans.rps.rede.services.dtos.MovimentacaoDTO

1 error: org.modelmapper.MappingException: ModelMapper mapping errors:

1) Error mapping br.gov.ans.rps.rede.services.entities.Movimentacao to br.gov.ans.rps.rede.services.dtos.MovimentacaoDTO

1 error
    at org.modelmapper.internal.Errors.throwMappingExceptionIfErrorsExist(Errors.java:374)
    at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:69)
    at org.modelmapper.ModelMapper.mapInternal(ModelMapper.java:497)
    at org.modelmapper.ModelMapper.map(ModelMapper.java:340)
    at br.gov.ans.rps.rede.services.business.SolicitacaoNegocio.converterMovimentacaoVO(SolicitacaoNegocio.java:394)

xecutor.java:617ServletInnoalHjava.lang.请求(ServletInnoalHhread.run)在hread.java:745ServletInnoalHjava.lang.0美元(ServletInnoalHjava.security.)在ontroller.doServletInnoalHandler$org.jboss.logmanager.formatters.请求(ServletInnoalH14.render)在ormatters.java:638Connectors.executeRootHandler(Connectors.java:207)在io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:802)在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)在java.util.concurrent.ThreadPoolExecitor$Worker.run(ThreadPoolEio.undertow.servlet.handlers.)在andler.dispatchTandler.java:264(Tio.undertow.servlet.handlers.)引起的andler.accessStackOverflow Error在andler.java:81AccessCio.undertow.servlet.handlers.Privileged(Native Method)在1.handleFor事宜$andler.java:175Raw(Fio.undertow.server.)

阿卡拜恩

public StreamedContent imprimirSolicitacao(SolicitacaoVO solicitacaoVO){
        
        StreamedContent download = new DefaultStreamedContent();

        try {
            SolicitacaoVO solicitacaoCompleta = solicitacaoClient.buscarSolicitacao(solicitacaoVO.getId().toString(), true);
                        
            ModelMapper modelMapper = new ModelMapper();
            
            SolicitacaoVO solicitacaoImprimir = modelMapper.map(solicitacaoCompleta, SolicitacaoVO.class);
            
            for(MovimentacaoVO mov:solicitacaoImprimir.getListaMovimentacao()){
                
                List<PlanoVO> planosSemDuplicados = new ArrayList<PlanoVO>();
                mov.setListaPrestadoresExclusao(new ArrayList<PrestadorVO>());
                for (PlanoVO planoVO : mov.getListaPlanos()) {
                    if(!planosSemDuplicados.contains(planoVO)){
                        planosSemDuplicados.add(planoVO);
                    }
                    if(!mov.getListaPrestadoresExclusao().contains(planoVO.getPrestador())){
                        mov.getListaPrestadoresExclusao().add(planoVO.getPrestador());                              
                    }
                }
                mov.setListaPlanos(planosSemDuplicados);
                
                if ( mov.getReconsideracao()!=null && !mov.getReconsideracao().getArquivos().isEmpty() ){
                    
                    int sizeList = mov.getReconsideracao().getArquivos().size();
                    int i = 1;
                    StringBuffer aux = new StringBuffer();
                    for ( ArquivoReconsideracaoVO arq : mov.getReconsideracao().getArquivos() ){
                        aux.append(arq.getNomeArquivo());
                        if ( i < sizeList ){
                            aux.append(";  ");
                        }else {
                            aux.append(".");
                        }
                        i++;
                    }
                    mov.getReconsideracao().setNomeArquivosConcatenados(aux.toString());
                }
                
                Collections.sort(mov.getListaPrestadoresExclusao());
                Collections.sort(mov.getListaPrestadores());
            }
            
            InputStream pdfGerado = gerarRelatorioSolicitacaoOuMovimentacao(solicitacaoImprimir);
            download = prepararDownload(pdfGerado, "Solicitação", TipoArquivo.PDF.getContentType());
        } catch (Exception e) {
            exibirMensagemErro("erro.imprimir.pdf");
            logger.error(e,e);
            return null;
        }
        return download;
    }

请求客户

@JsonIgnoreProperties(ignoreUnknown = true)
public class SolicitacaoClient implements Serializable{
    private static final long serialVersionUID = 1L;

    @Inject
    @PropertiesInfo(file="services.properties", key="rps.rede.services.rest.uri")
    @Server
    private String uri;
    
    @Inject
    @Autenticado(value = "rps.rede", type = AuthType.BEARER)
    private Client cliente;
        
    @Inject
    Logger logger;
    
    public List<OperadoraVO> consultarOperadoras(String filtroCodigo, String filtroCNPJ, String filtroNome) throws Exception{
        Response response = cliente.target(uri + "operadoras")
                .queryParam("codigo", filtroCodigo)
                .queryParam("cnpj", filtroCNPJ)
                .queryParam("nome", filtroNome)
                .request().get();
        try {
                if(response.getStatusInfo().getFamily() != Family.SUCCESSFUL){
                        throw new Exception(response.readEntity(ErrorMessage.class).getError());
                    } else{
                        String json = (String) response.readEntity(String.class);
                        ObjectMapper mapper = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
                        List<OperadoraVO> operadoras = mapper.readValue(json, new TypeReference<List<OperadoraVO>>() { });
                        
                        return operadoras;
                    }
        } finally {
            response.close();
        }

    }
    
    public SolicitacaoVO buscarSolicitacao(String id, boolean lgCompleto) throws Exception{
        WebTarget target = cliente.target(uri + "/solicitacoes/" + id);
        
        target = target.queryParam("lg-completa", lgCompleto ? 1 : 0);
        
        Response response = target.request().get();
        
        try {
            if(response.getStatusInfo().getFamily() != Family.SUCCESSFUL){
                throw new Exception(response.readEntity(ErrorMessage.class).getError());
            } else{
                String json = (String) response.readEntity(String.class);
                ObjectMapper mapper = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
                return mapper.readValue(json, SolicitacaoVO.class);
            }
        } finally {
            response.close();
        }
    }
    
    public List<SolicitacaoVO> buscarSolicitacoes(String coOperadora, FiltroSolicitacao filtro) throws Exception{
        
        Response response = cliente.target(uri + "operadoras/" + coOperadora + "/solicitacoes")
            .queryParam("cdSituacao", filtro.getStatus())
            .queryParam("dataEnvioInicio", Utils.dateToString(filtro.getDataInicio(), "dd/MM/yyyy"))
            .queryParam("dataEnvioFim", Utils.dateToString(filtro.getDataFim(), "dd/MM/yyyy HH:mm"))
            .queryParam("protocolo", Utils.getSomenteNumeros(filtro.getProtocolo()))
            .queryParam("gru", filtro.getGru())
            .request().get();

        try {
            if(response.getStatusInfo().getFamily() != Family.SUCCESSFUL){
                throw new Exception(response.readEntity(ErrorMessage.class).getError());
            } else{
                String json = (String) response.readEntity(String.class);
                ObjectMapper mapper = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
                return mapper.readValue(json, new TypeReference<List<SolicitacaoVO>>() { });
            }
        } finally {
            response.close();
        }
    }
    
    public ComprovanteRelatorio montarComprovanteRelatorio(Integer idSolicitacao) throws Exception{
        
        Response response = cliente.target(uri + "/solicitacoes/" + idSolicitacao + "/montarComprovanteRelatorio").request().get();
        
        try {
            if(response.getStatusInfo().getFamily() != Family.SUCCESSFUL){
                throw new Exception(response.readEntity(ErrorMessage.class).getError());
            } else{
                String json = (String) response.readEntity(String.class);
                ObjectMapper mapper = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
                return mapper.readValue(json, ComprovanteRelatorio.class);
            }           
        } finally {
            response.close();
        }
    }

    public List<MovimentacaoRelatorioVO> montarRelatorioMovimentacoes(Integer idSolicitacao) throws Exception {
        
        Response response = cliente.target(uri + "/solicitacoes/" + idSolicitacao + "/relatorioMovimentacoes").request().get();

        gerarLogResponse(uri + "/solicitacoes/" + idSolicitacao + "/relatorioMovimentacoes", response);

        try {
            if(response.getStatusInfo().getFamily() != Family.SUCCESSFUL){
                throw new Exception(response.readEntity(ErrorMessage.class).getError());
            } else{
                String json = (String) response.readEntity(String.class);
                ObjectMapper mapper = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
                return mapper.readValue(json, new TypeReference<List<MovimentacaoRelatorioVO>>() { });
            }
        } finally {
            response.close();
        }
    }

    public List<MovimentacaoRelatorioVO> montarRelatorioConsultaMovimentacoesInterno(List<MovimentacaoVO> listaMovimentacoes) throws Exception {
        
        ConsultaMovimentacaoRelatorioVO consultaMovimentacaoRelatorioVO = new ConsultaMovimentacaoRelatorioVO();
        consultaMovimentacaoRelatorioVO.setListaMovimentacao(listaMovimentacoes);
        
        Response response = cliente.target(uri + "/solicitacoes/movimentacoes/relatorio/interno")
                .request().post(Entity.entity(consultaMovimentacaoRelatorioVO, MediaType.APPLICATION_JSON));
        
        try {
            if(response.getStatusInfo().getFamily() != Family.SUCCESSFUL){
                throw new Exception(response.readEntity(ErrorMessage.class).getError());
            } else{
                String json = (String) response.readEntity(String.class);
                ObjectMapper mapper = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
                return mapper.readValue(json, new TypeReference<List<MovimentacaoRelatorioVO>>() { });
            }           
        } finally {
            response.close();
        }
    }
    
    private void gerarLogResponse(String url, Response response) {
        logger.info("URL chamada: " + url);
        logger.info("Header da resposta:");
        
        for (Entry<String, List<Object>> iterable_element : response.getHeaders().entrySet()) {
            for (Object iterable : iterable_element.getValue()) {
                logger.info(iterable_element.getKey() + " - " + iterable.toString());               
            }
        }
    }
}

PDF生成器JasperReport

public class ReportHelper {
    
    @Inject
    private static Logger LOGGER;

    public enum FORMATO_RELATORIO {
        XLS, PDF;
    }

    private static String gerarIdReport() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyyyyhhmmss");
        String id = simpleDateFormat.format(new Date());

        return id;
    }

    /**
     * Retorna caminho onde os relatórios (.jasper e .jrxml e tmps) ficam
     * armazenados
     * */
    private static String reportSourcePath() {

        return FacesContext.getCurrentInstance().getExternalContext().getRealPath("/jasper/") + "/";
    }

    /**
     * Retorna o caminho onde os relatórios finais ficam no servidor (ex: .PDF)
     * */
    private String reportFile() {
        return FacesContext.getCurrentInstance().getExternalContext().getInitParameter("reportDirectory");
    }

    /**
     * Abrir Janela com Arquivo (PDF, XLS, TXT e etc)
     * */
    public void abrirPoupUp(String fileName) {
        abrirPoupUp(fileName, null);
    }

    public void abrirPoupUp(String fileName, String nomeJanela){
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String contextPath = req.getContextPath().replace("/", "");
        if (nomeJanela == null){
            nomeJanela = "Relatório";
        }

        RequestContext.getCurrentInstance().execute(
            "window.open(/" + contextPath + "/jasper/" + fileName + ",'"+nomeJanela+"','width=800px,height=800px')");
        }

    /**
     * Gera o relatório e retorna o nome do relatório gerado
     * */
    private static InputStream gerarRelatorio(String relatorio, List<Object> beans, Map<String, Object> params, FORMATO_RELATORIO formatoExportacao) {
        try {
            if (params == null) {
                params = new HashMap<String, Object>();
            }

            JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(beans);
            
            DefaultJasperReportsContext.getInstance().setProperty("net.sf.jasperreports.components.sort.up.arrow.char", "");
            DefaultJasperReportsContext.getInstance().setProperty("net.sf.jasperreports.components.sort.down.arrow.char", "");

            String relatorioFormated = relatorio.endsWith(".jasper") ? relatorio : (new StringBuilder()).append(relatorio).append(".jasper").toString();
            net.sf.jasperreports.engine.JasperPrint jasperPrint = null;
            
            
            if (beans != null && beans.size() > 0) {
                jasperPrint = JasperFillManager.fillReport(reportSourcePath() + relatorioFormated, params, beanCollectionDataSource);
            } else {
                jasperPrint = JasperFillManager.fillReport(reportSourcePath() + relatorioFormated, params, new JREmptyDataSource());
            }

            StringBuilder nomeRelatorio = new StringBuilder();
            nomeRelatorio.append(relatorio + "_" + gerarIdReport());

            /*
             * JRExporter foi descontinuada. Utilizando JRPdfExporter e JRXlsExporter para tratar PDF e XLS separadamente.
             * -- Ricardo --
             */
            //JRExporter exporter = null;
            JRPdfExporter exporter_pdf = null;
            JRXlsExporter exporter_xls = null;

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        
            if (formatoExportacao.equals(FORMATO_RELATORIO.PDF)) {
                exporter_pdf = new JRPdfExporter();
                nomeRelatorio.append(".pdf");
                
                exporter_pdf.setExporterInput(new SimpleExporterInput(jasperPrint));
                exporter_pdf.setExporterOutput(new SimpleOutputStreamExporterOutput(stream));
                exporter_pdf.exportReport();
            }
                
            if (formatoExportacao.equals(FORMATO_RELATORIO.XLS)) {
                exporter_xls = new JRXlsExporter();
                nomeRelatorio.append(".xls");
                
                exporter_xls.setExporterInput(new SimpleExporterInput(jasperPrint));
                exporter_xls.setExporterOutput(new SimpleOutputStreamExporterOutput(stream));
                exporter_xls.exportReport();
            }

            //ByteArrayOutputStream stream = new ByteArrayOutputStream();
            //exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            //exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, stream);
            //exporter.exportReport();          

            return new ByteArrayInputStream(stream.toByteArray());
            
        } catch (Exception e) {
            LOGGER.error(e, e);
            return null;
        }
    }

    /**
     * Geração de Relatório em XLS
     */
    public static InputStream gerarRelatorioXLS(String relatorio, List<Object> beans, Map<String, Object> params) {

        return gerarRelatorio(relatorio, beans, params, FORMATO_RELATORIO.XLS);

    }

    /**
     * Padrão para Arquivos PDF
     * @throws FileNotFoundException 
     * */
    public static InputStream gerarRelatorioPDF(String relatorio, Object object) throws FileNotFoundException {
        List<Object> beans = new ArrayList<Object>();
        beans.add(object);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("SUBREPORT_DIR", reportSourcePath());
        params.put("LOGO",new FileInputStream(FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/images/logo-ans-sem-slogan.png")));

        return gerarRelatorio(relatorio, beans, params, FORMATO_RELATORIO.PDF);

    }

}

共有1个答案

羊煜
2023-03-14

我不知道你的数据模型,但也许你在对象模型中有一个循环,即obj1指的是obj2,而obj2又指的是obj1?简单的模型映射会导致无限递归,从而导致堆栈溢出。也许obj2的对象映射器应该使用只映射obj1子集的映射器,以避免递归。

 类似资料:
  • 我得到一个错误java。lang.OutOfMemoryError(无错误消息),同时生成我的项目的签名Android应用程序包(AAB)。这是完整的错误消息- ***任务“:app:signReleaseBundle”的执行失败。 执行com.android.build.gradle.internal.tasks.FinalizeBundleTask$BundleToolRunnablejava

  • kafka控制台生产者--代理列表本地主机:9092--主题com-hftl2 [2019-12-25 16:09:24476]向主题com-hftl2发送消息时出错,密钥为null,值为20299831字节,错误为:(org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)org。阿帕奇。Kafka。常见的错误。Recor

  • 我试图在Eclipse中调试一个简单的java程序,结果出现了以下错误: 本机方法中的致命错误:JDWP未初始化任何传输,jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)错误:传输错误202:连接失败:连接超时错误:JDWPTransport dt_socket未能初始化,TRANSPORT_nit(510)JDWP退出错误AGENT_ERROR_TRANSPO

  • 我用的是reactjs。我正在使用material表获取可编辑表中的数据。但是我得到了一个像图片一样的错误,我怎样才能修复这个错误呢? 我使用useState进行表格的编辑设置。你能帮我纠正一下错误吗? 我在接收数据时没有收到任何错误。我只是在表格上使用活动/非活动编辑。但是 为行提供错误。 下面是错误截图和我的源代码

  • 我们有生成PDF文档的系统(使用Ecrion引擎)。我们正在使用时代字体。现在需要文档存档,因此我们正在从PDF切换到PDF/A,并将字体从Times 更改为Times New Roman(相同的字体)。这就是问题出现的地方 - 每个PDF / A也包括使用的字体(因为PDF / A是用于存档的PDF,因此它与字体一起出现)。问题是每个文档现在都包含“Times New Roman”,“Times

  • 我使用iTextPDF生成PDF,从一些文本输入中获取数据。 当我运行应用程序并创建第一个PDF时,它会按预期生成。 然后我改变一些值并生成另一个值,这就是问题所在。第一个PDF上显示的最后一个条目被打印在第二个生成的PDF的第一个条目的顶部。 不知道为什么会这样?它是保存到缓冲区还是什么的,不是很确定。 下面是生成PDF的代码: 输出请见附件图像,第一个显示第一个文件生成,第二个显示第二个文件生