Java tutorial
/* * Copyright (C) 2016 Dominion Global * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dominion.salud.mpr.negocio.service.integracion.impl; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.model.v25.message.ACK; import com.dominion.salud.mpr.hl7.er7.ER7Parser; import com.dominion.salud.mpr.negocio.entities.admin.Centros; import com.dominion.salud.mpr.negocio.entities.integracion.AbstractIntegracionEntity; import com.dominion.salud.mpr.negocio.entities.integracion.BuzonErrores; import com.dominion.salud.mpr.negocio.entities.integracion.BuzonOut; import com.dominion.salud.mpr.negocio.entities.integracion.BuzonOutHis; import com.dominion.salud.mpr.negocio.repositories.integracion.BuzonOutRepository; import com.dominion.salud.mpr.negocio.service.integracion.BuzonErroresService; import com.dominion.salud.mpr.negocio.service.integracion.BuzonOutHisService; import com.dominion.salud.mpr.negocio.service.integracion.BuzonOutService; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; /** * * @author jcgonzalez */ @Service("buzonOutService") public class BuzonOutServiceImpl extends AbstractIntegracionServiceImpl<BuzonOut, Long> implements BuzonOutService { private static final Logger logger = LoggerFactory.getLogger(BuzonOutServiceImpl.class); @Autowired private BuzonOutRepository buzonOutRepository; @Autowired private BuzonOutHisService buzonOutHisService; @Autowired private BuzonErroresService buzonErroresService; /** * * @param centros * @return */ @Override public List<BuzonOut> findAllByIdCentro(Centros centros) { return buzonOutRepository.findAllByIdCentro(centros); } /** * */ @Override @Scheduled(cron = "${mpr.task.buzon.out.process.messages}") public void processMessages() { List<BuzonOut> buzonOuts = buzonOutRepository.findAllNoProcesados(); if (buzonOuts != null && !buzonOuts.isEmpty()) { logger.debug("Se han obtenido " + buzonOuts.size() + " mensajes para procesar"); int contador = 0; Iterator<BuzonOut> iterador = buzonOuts.iterator(); while (iterador.hasNext()) { contador++; BuzonOut buzonOut = iterador.next(); buzonOut.setFechaPro(new Date()); try { logger.debug(" Procesando mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de " + buzonOuts.size()); if (StringUtils.isBlank(buzonOut.getCentros().getUrl())) { throw new Exception("No se ha indicado la URL de destino (" + buzonOut.getCentros().getUrl() + ") para el centro (" + buzonOut.getCentros().getCodCentro() + ") " + buzonOut.getCentros().getTxtCentro()); } logger.debug(" Iniciando el envio a: " + buzonOut.getCentros().getUrl()); String response = ""; switch (buzonOut.getTipo()) { case "ZFN_O13": //Acuerdo RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); try { logger.debug(" Enviando el mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de " + buzonOuts.size()); response = restTemplate.postForObject(new URI(buzonOut.getCentros().getUrl()), buzonOut.getMensaje(), String.class); logger.debug(" Respuesta recibida: " + response); } catch (URISyntaxException | RestClientException e) { throw new RestClientException("No se ha podido enviar el mensaje al destinatario [" + buzonOut.toString() + "]: " + (StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString())); } break; default: logger.error("No se reconoce el formato del mensaje: " + buzonOut.getTipo()); throw new Exception("No se reconoce el formato del mensaje: " + buzonOut.getTipo()); } //Evalua la respuesta recibida try { logger.debug(" Procesando al respuesta del mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de " + buzonOuts.size()); ACK ack = (ACK) new ER7Parser().parse(response); if (!StringUtils.equals(ack.getMSA().getAcknowledgmentCode().getValue(), "AA") && !StringUtils.equals(ack.getMSA().getAcknowledgmentCode().getValue(), "CA")) { //AA - Application Accept o CA - Commit Accept logger.error("Se han producido errores al procesar el mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + " en destino: " + ack.getERR().getDiagnosticInformation().getValue()); throw new Exception(ack.getERR().getDiagnosticInformation().getValue()); } buzonOut.setEstado(AbstractIntegracionEntity.MENSAJE_PROCESADO); } catch (HL7Exception e) { logger.error("No se ha podido procesar la respuesta del mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + ": " + e.getMessage()); throw new Exception("No se ha podido procesar la respuesta del mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + ": " + e.getMessage()); } } catch (Exception e) { logger.error((StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString())); buzonOut.setEstado(AbstractIntegracionEntity.MENSAJE_ERRONEO); //BuzonErrores BuzonErrores buzonErrores = new BuzonErrores(); buzonErrores.setBuzonOut(buzonOut); buzonErrores.setEstado(AbstractIntegracionEntity.MENSAJE_NO_PROCESADO); buzonErrores.setFechaError(new Date()); buzonErrores.setMensaje("<b>SE HAN PRODUCIDO ERRORES AL PROCESAR EL MENSAJE (Saliente)</b><br>" + (StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString())); buzonErroresService.save(buzonErrores); } finally { buzonOutRepository.save(buzonOut); } } } } /** * */ @Override @Transactional @Scheduled(cron = "${mpr.task.buzon.out.clean}") public void clean() { logger.debug("Volcando al historico mensajes procesados de BUZON_OUT"); List<BuzonOut> buzonOuts = buzonOutRepository.findAllProcesados(); if (buzonOuts != null && !buzonOuts.isEmpty()) { Iterator<BuzonOut> iterador = buzonOuts.iterator(); while (iterador.hasNext()) { BuzonOut buzonOut = iterador.next(); BuzonOutHis buzonOutHis = new BuzonOutHis(); buzonOutHis.setIdBuzonOut(buzonOut.getIdBuzonOut()); buzonOutHis.setCentros(buzonOut.getCentros()); buzonOutHis.setFechaOut(buzonOut.getFechaOut()); buzonOutHis.setFechaPro(buzonOut.getFechaPro()); buzonOutHis.setIdMensaje(buzonOut.getIdMensaje()); buzonOutHis.setTipo(buzonOut.getTipo()); buzonOutHis.setMensaje(buzonOut.getMensaje()); buzonOutHisService.save(buzonOutHis); buzonOutRepository.delete(buzonOut); } } logger.debug("Mensajes procesados de BUZON_OUT volcados al historico correctamente"); } }