Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.postalis.folhapgto.service; import br.com.correios.populisws.services.ResultadoIncluirAcompanhamento; import br.com.postalis.folhapgto.entidade.ConsignacaoPopulis; import br.com.postalis.folhapgto.entidade.PosGpxConsignacaoPopulisControle; import br.com.postalis.folhapgto.entidade.PosGpxConsignacaoPopulisIncorporada; import br.com.postalis.folhapgto.entidade.RelatorioDTO; import br.com.postalis.folhapgto.repository.ConsignacaoPopulisRepository; import br.com.postalis.folhapgto.repository.ControleRepository; import br.com.postalis.folhapgto.repository.CriticaRepository; import br.com.postalis.folhapgto.repository.IncorporadosRepository; import br.com.postalis.folhapgto.repository.RetornoFinanceiroRepository; import br.com.postalis.folhapgto.util.DataUtil; import br.com.postalis.folhapgto.util.FileUtil; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.swing.ImageIcon; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; /** * * @author jonathan.salcedo */ @Component public class SvcFolhaPgtoImpl implements Serializable { private static final long serialVersionUID = 1L; private ApplicationContext appContext; private final Logger LOGGER = LoggerFactory.getLogger(this.getClass()); private JobExecution execution = null; @Autowired private ConsignacaoPopulisRepository consignadoRepository; @Autowired private ControleRepository controleRepository; @Autowired private CriticaRepository criticaRepository; @Autowired private IncorporadosRepository incorporadosRepository; @Autowired private RetornoFinanceiroRepository retornoFinanceiroRepository; //@Autowired //private JobRepository jobRepository; private ExitStatus resultado; public ExitStatus exportarFolhaPgto(String usuario, long anoMesRef, Date dtRef) { return executarJob("ImportarRubricasFolhaPgto", usuario, anoMesRef, dtRef); } public ExitStatus consultarLogImportacao(String usuario, long anoMesRef, Date dtRef) { return executarJob("consultarLogImportacao", usuario, anoMesRef, dtRef); } public ExitStatus consultarDescPosFolha(String usuario, long anoMesRef, Date dtRef) { return executarJob("consultarListaDescPosFolha", usuario, anoMesRef, dtRef); } public ExitStatus consultarRubricasIncorporadas(String usuario, long anoMesRef, Date dtRef) { return executarJob("consultarRubIncorporadas", usuario, anoMesRef, dtRef); } private ExitStatus executarJob(String nomeJob, String usuario, long anoMesRef, Date dtRef) { try { appContext = new ClassPathXmlApplicationContext("spring/batch/jobs/jobMov.xml"); JobLauncher jobLauncher = (JobLauncher) appContext.getBean("jobLauncher"); Job job = (Job) appContext.getBean(nomeJob); LOGGER.info("Iniciando o Processo " + nomeJob + "..."); JobParameters jobParams = new JobParametersBuilder() .addDate("dtReferencia", dtRef).addLong("anoMesRef", anoMesRef).addString("usuario", usuario) .toJobParameters(); execution = jobLauncher.run(job, jobParams); LOGGER.info("Hora inicial: " + execution.getStartTime()); LOGGER.info("Status do processamento : " + execution.getStatus()); LOGGER.info("Hora Final: " + execution.getEndTime()); LOGGER.info("Fim do Processo!!!"); LOGGER.info(execution.toString()); String nomeLog = ""; SimpleDateFormat formatComHora = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat formatSemHora = new SimpleDateFormat("dd-MM-yyyy"); if (nomeJob.equalsIgnoreCase("ImportarRubricasFolhaPgto")) { nomeLog = (String) execution.getExecutionContext().get("nomeLog"); } else if (nomeJob.equalsIgnoreCase("consultarDescPosFolha")) { nomeLog = "ImportarDescPosFolhaECT_" + formatSemHora.format(dtRef) + "_" + formatComHora.format(DateTime.now().toDate()); } else if (nomeJob.equalsIgnoreCase("consultarLogImportacao")) { nomeLog = "ImportarLogImportacaoECT_" + formatSemHora.format(dtRef) + "_" + formatComHora.format(DateTime.now().toDate()); } else if (nomeJob.equalsIgnoreCase("consultarRubIncorporadas")) { nomeLog = "ImportarRubricasIncorporadasECT_" + formatSemHora.format(dtRef) + "_" + formatComHora.format(DateTime.now().toDate()); } else { nomeLog = "LogGeral_" + formatSemHora.format(dtRef) + "_" + formatComHora.format(DateTime.now().toDate()); } renomearArquivoDeLog(nomeLog); resultado = new ExitStatus(execution.getExitStatus().getExitCode()); } catch (Exception e) { LOGGER.error("Erro ProcBatchJobMov: " + e.getMessage()); } finally { //execution.setExecutionContext(null); for (StepExecution stepExecution : execution.getStepExecutions()) { stepExecution.setExecutionContext(null); // jobRepository.updateExecutionContext(stepExecution); } //jobRepository.updateExecutionContext(execution); } return resultado; } public boolean existemLancamentoParaExportar(Date dtRef) { return consignadoRepository.existsByRef(dtRef); } public List<PosGpxConsignacaoPopulisControle> buscarHistoricoProcessamento() { return controleRepository.findAllByOrderBySqControleDesc(); } private void renomearArquivoDeLog(String nomeLog) { try { String pasta = "C:\\POSTALIS\\LOGS\\"; String logPadrao = "app-info.log"; FileUtil.copyFileAnotherName(pasta, pasta, logPadrao, nomeLog + ".log"); } catch (Exception e) { LOGGER.error("Erro ao renomear aquivo de Log:", e); } } public boolean criarRelatorioDeCriticas(Date dtRef) throws JRException { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); lista.addAll(criticaRepository.findRelByDtReferencia(dtRef)); if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de crticas de processamento", "RelatorioCriticas", lista, dtRef); return true; } public boolean criarRelatorioDeRubricasNaoIncorporadas(Date dtRef) throws JRException { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); lista.addAll(consignadoRepository.findRelRubEnvNaoIncorpByDtReferenciaOrderByVerbaAndMatricula(dtRef)); if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de rubricas enviadas e no incorporadas", "RelEnvNaoIncorporadas", lista, dtRef); return true; } public boolean criarRelatorioDeRubricasIncorporadasNaoEnviadas(Date dtRef) throws JRException { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); lista.addAll( incorporadosRepository.findRelRubIncorpNaoEnviadasByDtReferenciaOrderByVerbaAndMatricula(dtRef)); if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de rubricas incorporadas e no enviadas", "RelIncorporadasNaoEnv", lista, dtRef); return true; } public boolean criarRelatorioDeDifEnviadasEIncorporadas(Date dtRef) throws JRException { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); lista.addAll(consignadoRepository.findRelDifEnvIncorpByDtReferenciaOrderByVerbaAndMatricula(dtRef)); if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de diferenas das rbricas enviadas e incorporadas - Analtico", "RelDifEnviadaXIncorporadas", lista, dtRef); return true; } public boolean criarRelatorioResumoDeDifEnviadasEIncorporadas(Date dtRef) throws JRException { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); LinkedHashMap<String, PosGpxConsignacaoPopulisIncorporada> listaIncorp = new LinkedHashMap<String, PosGpxConsignacaoPopulisIncorporada>(); for (PosGpxConsignacaoPopulisIncorporada incorp : incorporadosRepository .findByDtReferenciaGroupByVerbaAndVlLancamentoAndQtLancamento(dtRef)) { listaIncorp.put(incorp.getCdVerba(), incorp); } for (ConsignacaoPopulis env : consignadoRepository .findByDtReferenciaEnviadosGroupByCdVerbaAndDsVerba(dtRef)) { PosGpxConsignacaoPopulisIncorporada inc = listaIncorp.get(env.getCdVerba()); RelatorioDTO rel; if (inc != null) { BigDecimal difValor = env.getVlVerba().subtract(inc.getVlLancamento()); BigDecimal difQtd = env.getQtVerba().subtract(inc.getQtLancamento()); rel = new RelatorioDTO(env.getCdVerba(), env.getDsVerba(), env.getVlVerba(), env.getQtVerba(), inc.getVlLancamento(), inc.getQtLancamento(), difValor, difQtd); } else { rel = new RelatorioDTO(env.getCdVerba(), env.getDsVerba(), env.getVlVerba(), env.getQtVerba(), BigDecimal.ZERO, BigDecimal.ZERO, env.getVlVerba(), env.getQtVerba()); } lista.add(rel); } if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de diferenas das rbricas enviadas e incorporadas - Sinttico", "RelResumoDifRubEnviadasXIncorporadas", lista, dtRef); return true; } private void gerarRelatorio(String nomeRel, String relJrxml, List<?> lista, Date dtRef) { JasperReport report = null; String caminhoCompletoRel = ""; try { String pasta = "C:\\POSTALIS\\RELATORIOS\\"; report = JasperCompileManager .compileReport(getClass().getResourceAsStream("/relatorios/" + relJrxml + ".jrxml")); ImageIcon gto = new ImageIcon(getClass().getResource("/imagens/Logo branca.jpg")); Map parametros = new HashMap(); parametros.put("logo", gto.getImage()); parametros.put("referencia", DataUtil.getDataS(dtRef, "MM/yyyy")); caminhoCompletoRel = pasta + nomeRel + "_" + DataUtil.getDataS(dtRef, "ddMMyyyy") + "_" + DataUtil.getDiaProcessamentoComHoraMinutoSegundo() + ".pdf"; JasperPrint print = JasperFillManager.fillReport(report, parametros, new JRBeanCollectionDataSource(lista)); JasperExportManager.exportReportToPdfFile(print, caminhoCompletoRel); File pdf = new File(caminhoCompletoRel); Desktop.getDesktop().open(pdf); } catch (JRException ex) { LOGGER.error("Erro construir o relatorio Jasper: " + ex); } catch (IOException ex) { LOGGER.error("Erro ao abrir o relatorio em PDF a partir da pasta: " + caminhoCompletoRel + ". Motivo: " + ex); } } public ResultadoIncluirAcompanhamento incluirAcompanhamentoWS(int anoMes, int numInclusao) throws Exception { SvcWebserviceImpl service = new SvcWebserviceImpl(); return service.incluirAcompanhamento(anoMes, numInclusao); } public static void main(String[] args) throws JRException { SvcFolhaPgtoImpl rel = new SvcFolhaPgtoImpl(); //rel.criarRelatorioDeCriticas(null); //rel.criarRelatorioDeRubricasNaoIncorporadas(null); //rel.criarRelatorioDeRubricasIncorporadasNaoEnviadas(null); //rel.criarRelatorioDeDifEnviadasEIncorporadas(null); //rel.criarRelatorioResumoDeDifEnviadasEIncorporadas(null); } public boolean criarRelatorioResumoExportacao(Date dtRef) { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); lista.addAll(consignadoRepository.findRelResumoExportacao(dtRef)); if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de resumo da exportao", "RelResumoExportacao", lista, dtRef); return true; } public boolean criarRelatorioResumoIncorporacao(Date dtRef) { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); lista.addAll(incorporadosRepository.findRelResumoIncorporacao(dtRef)); if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de resumo da incorporao", "RelResumoIncorporacao", lista, dtRef); return true; } public boolean criarRelatorioResumoImportacao(Date dtRef) { List<RelatorioDTO> lista = new ArrayList<RelatorioDTO>(); lista.addAll(retornoFinanceiroRepository.findRelResumoImportacao(dtRef)); if (lista == null || lista.isEmpty()) { return false; } gerarRelatorio("Relatrio de resumo da importao", "RelResumoImportacao", lista, dtRef); return true; } }