com.dominion.salud.mpr.ws.rest.MPRMessagesRESTHandlerService.java Source code

Java tutorial

Introduction

Here is the source code for com.dominion.salud.mpr.ws.rest.MPRMessagesRESTHandlerService.java

Source

/*
 * 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.ws.rest;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v25.group.RAS_O17_ORDER;
import ca.uhn.hl7v2.model.v25.message.ACK;
import ca.uhn.hl7v2.model.v25.message.RAS_O17;
import ca.uhn.hl7v2.model.v25.segment.MSH;
import ca.uhn.hl7v2.model.v25.segment.ORC;
import ca.uhn.hl7v2.model.v25.segment.PID;
import ca.uhn.hl7v2.model.v25.segment.PV1;
import ca.uhn.hl7v2.model.v25.segment.RXA;
import ca.uhn.hl7v2.model.v25.segment.RXC;
import ca.uhn.hl7v2.model.v25.segment.RXD;
import ca.uhn.hl7v2.model.v25.segment.RXO;
import ca.uhn.hl7v2.model.v25.segment.TQ1;
import ca.uhn.hl7v2.parser.EncodingDetector;
import com.dominion.salud.mpr.hl7.AbstractParser;
import com.dominion.salud.mpr.hl7.er7.ER7Parser;
import com.dominion.salud.mpr.hl7.v25.group.ZDS_O13_ORDER;
import com.dominion.salud.mpr.hl7.v25.group.ZMP_O09_ORDER;
import com.dominion.salud.mpr.hl7.v25.message.ZDS_O13;
import com.dominion.salud.mpr.hl7.v25.message.ZFN_M13;
import com.dominion.salud.mpr.hl7.v25.message.ZMP_O09;
import com.dominion.salud.mpr.hl7.v25.segment.Z01;
import com.dominion.salud.mpr.hl7.v25.segment.ZFA;
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.BuzonIn;
import com.dominion.salud.mpr.negocio.service.admin.CentrosService;
import com.dominion.salud.mpr.negocio.service.integracion.BuzonInService;
import com.dominion.salud.mpr.ws.MPRMessagesHL7Service;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author jcgonzalez
 */
@RestController
public class MPRMessagesRESTHandlerService extends MPRMessagesHL7Service {

    private static final Logger logger = LoggerFactory.getLogger(MPRMessagesRESTHandlerService.class);

    @Autowired
    private BuzonInService buzonInService;
    @Autowired
    private CentrosService centrosService;

    @ResponseBody
    @RequestMapping(value = "/receiveMessages", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<String> receiveMessages(@RequestBody(required = true) String message) {
        logger.info("RECIBIENDO MENSAJE ENTRANTE");
        logger.info(message);

        ACK ack = null;
        AbstractParser parser = null;
        Message hl7message = null;
        String cod_centro = "";

        try {
            message = StringUtils.replace(message, "\n", "\r");
            if (StringUtils.isBlank(message)) { //Validaciones previas
                throw new HL7Exception("No se ha indicado un mensaje entrante: [" + message + "]");
            }

            //Deternima el formato del mensaje
            logger.debug("     Determinando el formato del mensaje y el parseador a emplear");
            if (EncodingDetector.isEr7Encoded(message)) {
                parser = new ER7Parser();
                logger.debug("          Formato del mensaje ER7 y parseador [" + parser.getClass() + "] aceptados");
            } else {
                throw new HL7Exception("Formato de mensaje no reconocido. El formato soportado es ER7");
            }
            logger.debug("     Formato del mensaje y parseador determinados correctamente");

            //Parseado del mensaje
            logger.debug("     Parseando mensaje [" + parser.getClass() + "]");
            hl7message = parser.parse(message);
            logger.debug("     Mensaje parseado correctamente [" + hl7message.getClass() + "]");

            //Validaciones del MPR
            logger.debug("     Validando el mensaje");
            MSH msh = (MSH) hl7message.get("MSH");
            if (StringUtils.isBlank(msh.getMessageControlID().getValue())) { //MSH.10
                throw new HL7Exception(
                        "No se ha indicado el identificador de mensaje (MSH-10: Message Control ID)");
            }

            if (hl7message.getClass() == ZDS_O13.class) { //DISPENSACIONES
                ZDS_O13 zds_o13 = (ZDS_O13) hl7message;

                PID pid = zds_o13.getPATIENT().getPID();
                PV1 pv1 = zds_o13.getPATIENT().getPATIENT_VISIT().getPV1();

                Integer nhc = null;
                String cipa = null;
                for (int i = 0; i < pid.getPatientIdentifierList().length; i++) { // PID.3 - PatientIdentifierList
                    if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "PI")) {
                        if (StringUtils.isNotBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                            try {
                                nhc = NumberUtils
                                        .createInteger(pid.getPatientIdentifierList(i).getIDNumber().getValue());
                            } catch (Exception e) {
                                logger.warn("El NHC no es correcto (PID-3.1: Patient Identifier List [PI])");
                            }
                        }
                    } else if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "CIPA")) {
                        if (StringUtils.isNotBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                            cipa = pid.getPatientIdentifierList(i).getIDNumber().getValue();
                        } else {
                            logger.warn("El CIPA no es correcto (PID-3.1: Patient Identifier List [CIPA])");
                        }
                    }
                }

                if (nhc == null && StringUtils.isBlank(cipa)) {
                    throw new HL7Exception(
                            "No se ha indicado el NHC (PID-3.1: Patient Identifier List [PI]) ni el CIPA (PID-3.1: Patient Identifier List [CIPA])");
                }

                //PV1.2 - Clase de Paciente
                if (StringUtils.isNotBlank(pv1.getPatientClass().getValue())) { //PV1.2 - Clase de Paciente
                    if (StringUtils.equals(pv1.getPatientClass().getValue(), "O")) { //Outpatient
                        if (StringUtils.isBlank(pv1.getPatientType().getValue())) { //PV1.18 - Tipo de Paciente
                            throw new HL7Exception("No se ha indicado el tipo de paciente (PV1-18: Patient Type)");
                        }
                    }
                } else {
                    throw new HL7Exception("No se ha indicado la clase de paciente (PV1-2: Patient Class)");
                }

                //PV1.19.1 - Codigo de Episodio
                if (StringUtils.isBlank(pv1.getVisitNumber().getIDNumber().getValue())) {
                    throw new HL7Exception("No se ha indicado el episodio del paciente (PV1.19: Visit Number)");
                }

                List<ZDS_O13_ORDER> zds_o13_orders = zds_o13.getORDERAll();
                for (ZDS_O13_ORDER zds_o13_order : zds_o13_orders) {
                    ORC orc = zds_o13_order.getORC();
                    TQ1 tq1 = zds_o13_order.getTIMING().getTQ1();
                    RXD rxd = zds_o13_order.getRXD();
                    Z01 z01 = zds_o13_order.getZ01();

                    //ORC.21.10 - OrganizationIdentifier
                    if (StringUtils
                            .isBlank(orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue())) { //ORC.21.10
                        throw new HL7Exception(
                                "No se ha indicado el centro de origen (ORC-21.10: OrganizationIdentifier)");
                    } else {
                        cod_centro = orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue();
                    }

                    //ORC.2.1 - Codigo de Prescripcion
                    if (StringUtils.isBlank(orc.getPlacerOrderNumber().getEntityIdentifier().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado el identificador de la prescripcion (ORC-2.1: Placer Order Number)");
                    }

                    //ORC.3.1 - Codigo de Dispensacion
                    if (StringUtils.isBlank(orc.getFillerOrderNumber().getEntityIdentifier().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado el identificador de la dispensacion (ORC-3.1: Filler Order Number)");
                    }

                    //ORC.10 - Medico Prescriptor
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getIDNumber().getValue())) { //ORC.10.1
                        throw new HL7Exception(
                                "No se ha indicado el codigo del medico prescriptor (ORC-10.1: Entered By)");
                    }
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getGivenName().getValue())) { //ORC.10.3
                        throw new HL7Exception(
                                "No se ha indicado el nombre del medico prescriptor (ORC-10.3: Entered By)");
                    }
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getFamilyName().getSurname().getValue())) { //ORC.10.2.1
                        throw new HL7Exception(
                                "No se ha indicado el apellido del medico prescriptor (ORC-10.2.1: Entered By)");
                    }

                    //RXD.2.1 - DispenseGiveCode (Codigo Nacional de la Marca)
                    if (StringUtils.isBlank(rxd.getDispenseGiveCode().getIdentifier().getValue())) { //RXD.2.1
                        throw new HL7Exception(
                                "No se ha indicado el codigo nacional de la marca (RXD-2.1: DispenseGiveCode)");
                    }
                    //RXD.2.2 - DispenseGiveCode (Descripcion de la Marca)
                    if (StringUtils.isBlank(rxd.getDispenseGiveCode().getText().getValue())) { //RXD.2.2
                        throw new HL7Exception(
                                "No se ha indicado la descripcion de la marca (RXD-2.2: DispenseGiveCode)");
                    }

                    //RXD.3 - Fecha de la Dispensacion
                    if (StringUtils.isBlank(rxd.getDateTimeDispensed().getTime().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado la fecha de la dispensacion (RXD-3: Date/Time Dispensed)");
                    }

                    //RXD.4 - ActualDispenseAmount (Unidades Dispensadas en Forma Farmaceutica)
                    if (StringUtils.isNotBlank(rxd.getActualDispenseAmount().getValue())) { //RXD.4
                        try {
                            NumberUtils.createDouble(rxd.getActualDispenseAmount().getValue());
                        } catch (Exception e) {
                            throw new HL7Exception("Las unidades dispensadas no son correctas ["
                                    + rxd.getActualDispenseAmount().getValue() + "] (RXD-4: ActualDispenseAmount)");
                        }
                    } else {
                        throw new HL7Exception(
                                "No se han indicado las unidades dispensadas (RXD-4: ActualDispenseAmount)");
                    }

                    //TQ1.7 - Fecha de Inicio de la Prescripcion
                    if (StringUtils.isBlank(tq1.getStartDateTime().getTime().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado la fecha de inicio de la prescripcion (TQ1-7: Start Date/Time)");
                    }

                    //Z01.9 - Dosis Prescrita en Unidad de Medida
                    if (StringUtils.isNotBlank(z01.getDosisPrescrita().getValue())) { //Z01.9
                        try {
                            NumberUtils.createDouble(z01.getDosisPrescrita().getValue());
                        } catch (Exception e) {
                            throw new HL7Exception(
                                    "La dosis prescrita no es correcta [" + z01.getDosisPrescrita().getValue()
                                            + "] (Z01-9: Dosis Prescrita en Unidad de Medida)");
                        }
                    } else {
                        throw new HL7Exception(
                                "No se ha indicado dosis prescrita (Z01-9: Dosis Prescrita en Unidad de Medida)");
                    }
                }
            } else if (hl7message.getClass() == ZMP_O09.class) { //PRESCRIPCIONES (razon fin)
                ZMP_O09 zmp_o09 = (ZMP_O09) hl7message;

                PID pid = zmp_o09.getPATIENT().getPID();
                PV1 pv1 = zmp_o09.getPATIENT().getPATIENT_VISIT().getPV1();

                //PID.3 - Identificadores del paciente (NHC) y (CIPA)
                Integer nhc = null;
                String cipa = null;
                for (int i = 0; i < pid.getPatientIdentifierList().length; i++) { // PID.3 - PatientIdentifierList
                    if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "PI")) {
                        if (StringUtils.isNotBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                            try {
                                nhc = NumberUtils
                                        .createInteger(pid.getPatientIdentifierList(i).getIDNumber().getValue());
                            } catch (Exception e) {
                                throw new HL7Exception("El NHC no es correcto (PID-3.1: Patient Identifier List)");
                            }
                        } else {
                            throw new HL7Exception("No se ha indicado el NHC (PID-3.1: Patient Identifier List)");
                        }
                    } else if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "CIPA")) {
                        if (StringUtils.isBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                            throw new HL7Exception("El CIPA no es correcto (PID-3.1: Patient Identifier List)");
                        } else {
                            cipa = pid.getPatientIdentifierList(i).getIDNumber().getValue();
                        }
                    }
                }
                if (nhc == null) {
                    throw new HL7Exception("No se ha indicado el NHC (PID-3.1: Patient Identifier List)");
                }
                if (StringUtils.isBlank(cipa)) {
                    throw new HL7Exception("No se ha indicado el CIPA (PID-3.1: Patient Identifier List)");
                }

                //PV1.2 - Clase de Paciente
                if (StringUtils.isNotBlank(pv1.getPatientClass().getValue())) { //PV1.2 - Clase de Paciente
                    if (StringUtils.equals(pv1.getPatientClass().getValue(), "O")) { //Outpatient
                        if (StringUtils.isBlank(pv1.getPatientType().getValue())) { //PV1.18 - Tipo de Paciente
                            throw new HL7Exception("No se ha indicado el tipo de paciente (PV1-18: Patient Type)");
                        }
                    }
                } else {
                    throw new HL7Exception("No se ha indicado la clase de paciente (PV1-2: Patient Class)");
                }

                //PV1.19.1 - Codigo de Episodio
                if (StringUtils.isBlank(pv1.getVisitNumber().getIDNumber().getValue())) {
                    throw new HL7Exception("No se ha indicado el episodio del paciente (PV1.19: Visit Number)");
                }

                List<ZMP_O09_ORDER> zmp_o09_orders = zmp_o09.getORDERAll();
                for (ZMP_O09_ORDER zmp_o09_order : zmp_o09_orders) {
                    ORC orc = zmp_o09_order.getORC();
                    Z01 z01 = zmp_o09_order.getZ01();
                    TQ1 tq1 = zmp_o09_order.getTIMING().getTQ1();
                    RXC rxc = zmp_o09_order.getCOMPONENT().getRXC();

                    //ORC.21.10 - OrganizationIdentifier
                    if (StringUtils
                            .isBlank(orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue())) { //ORC.21.10
                        throw new HL7Exception(
                                "No se ha indicado el centro de origen (ORC-21.10: OrganizationIdentifier)");
                    } else {
                        cod_centro = orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue();
                    }

                    //ORC.2.1 - Codigo de Prescripcion
                    if (StringUtils.isBlank(orc.getPlacerOrderNumber().getEntityIdentifier().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado el identificador de la prescripcion (ORC-2.1: Placer Order Number)");
                    }

                    //ORC.10 - Medico Prescriptor
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getIDNumber().getValue())) { //ORC.10.1
                        throw new HL7Exception(
                                "No se ha indicado el codigo del medico prescriptor (ORC-10.1: Entered By)");
                    }
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getGivenName().getValue())) { //ORC.10.3
                        throw new HL7Exception(
                                "No se ha indicado el nombre del medico prescriptor (ORC-10.3: Entered By)");
                    }
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getFamilyName().getSurname().getValue())) { //ORC.10.2.1
                        throw new HL7Exception(
                                "No se ha indicado el apellido del medico prescriptor (ORC-10.2.1: Entered By)");
                    }

                    //RXC.2.1 - DispenseGiveCode (Codigo Nacional de la Marca)
                    if (StringUtils.isBlank(rxc.getComponentCode().getIdentifier().getValue())) { //RXC.2.1
                        throw new HL7Exception(
                                "No se ha indicado el codigo nacional de la marca (RXC-2.1: ComponentCode)");
                    }
                    //RXC.2.2 - DispenseGiveCode (Descripcion de la Marca)
                    if (StringUtils.isBlank(rxc.getComponentCode().getText().getValue())) { //RXC.2.2
                        throw new HL7Exception("No se ha indicado la descripcion de la marca (RXC-2.2: Text)");
                    }

                    //TQ1.7 - Fecha de Inicio de la Prescripcion
                    if (StringUtils.isBlank(tq1.getStartDateTime().getTime().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado la fecha de inicio de la prescripcion (TQ1-7: Start date/time)");
                    }
                    //TQ1.8 - Fecha de Fin de la Prescripcion
                    if (StringUtils.isBlank(tq1.getEndDateTime().getTime().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado la fecha de fin de la prescripcion (TQ1-8: End date/time)");
                    }

                    //Z01.9 - Dosis Prescrita en Unidad de Medida
                    if (StringUtils.isNotBlank(z01.getDosisPrescrita().getValue())) { //Z01.9
                        try {
                            NumberUtils.createDouble(z01.getDosisPrescrita().getValue());
                        } catch (Exception e) {
                            throw new HL7Exception(
                                    "La dosis prescrita no es correcta [" + z01.getDosisPrescrita().getValue()
                                            + "] (Z01-9: Dosis Prescrita en Unidad de Medida)");
                        }
                    } else {
                        throw new HL7Exception(
                                "No se ha indicado dosis prescrita (Z01-9: Dosis Prescrita en Unidad de Medida)");
                    }
                }
            } else if (hl7message.getClass() == ZFN_M13.class) { //RESPUESTAS DE EVALUACIONES
                ZFN_M13 zfn_m13 = (ZFN_M13) hl7message;

                ZFA zfa = zfn_m13.getACUERDO().getZFA();

                //ZFA.1.1 - MasterIdentifier
                if (StringUtils.isBlank(zfa.getMasterIdentifier().getAlternateIdentifier().getValue())) { //ZFA.1.1
                    throw new HL7Exception("No se ha indicado el codigo de acuerdo (ZFA.1.1: AlternateIdentifier)");
                }

                //ZFA.2.1 - Master file application identifier
                if (StringUtils.isBlank(zfa.getMasterFileApplicationIdentifier().getNamespaceID().getValue())) { //ZFA.2.1
                    throw new HL7Exception("No se ha indicado el centro de origen (ZFA.2.1: NamespaceID)");
                } else {
                    cod_centro = zfa.getMasterFileApplicationIdentifier().getNamespaceID().getValue();
                }
            } else if (hl7message.getClass() == RAS_O17.class) { //RESPUESTAS DE EVALUACIONES
                RAS_O17 ras_o17 = (RAS_O17) hl7message;

                PID pid = ras_o17.getPATIENT().getPID();
                PV1 pv1 = ras_o17.getPATIENT().getPATIENT_VISIT().getPV1();

                //PID.3 - Identificadores del paciente (NHC) y (CIPA)
                Integer nhc = null;
                String cipa = null;
                for (int i = 0; i < pid.getPatientIdentifierList().length; i++) { // PID.3 - PatientIdentifierList
                    if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "PI")) {
                        if (StringUtils.isNotBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                            try {
                                nhc = NumberUtils
                                        .createInteger(pid.getPatientIdentifierList(i).getIDNumber().getValue());
                            } catch (Exception e) {
                                throw new HL7Exception("El NHC no es correcto (PID-3.1: Patient Identifier List)");
                            }
                        } else {
                            throw new HL7Exception("No se ha indicado el NHC (PID-3.1: Patient Identifier List)");
                        }
                    } else if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "CIPA")) {
                        if (StringUtils.isBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                            throw new HL7Exception("El CIPA no es correcto (PID-3.1: Patient Identifier List)");
                        } else {
                            cipa = pid.getPatientIdentifierList(i).getIDNumber().getValue();
                        }
                    }
                }
                if (nhc == null) {
                    throw new HL7Exception("No se ha indicado el NHC (PID-3.1: Patient Identifier List)");
                }
                if (StringUtils.isBlank(cipa)) {
                    throw new HL7Exception("No se ha indicado el CIPA (PID-3.1: Patient Identifier List)");
                }

                //PV1.2 - Clase de Paciente
                if (StringUtils.isNotBlank(pv1.getPatientClass().getValue())) { //PV1.2 - Clase de Paciente
                    if (StringUtils.equals(pv1.getPatientClass().getValue(), "O")) { //Outpatient
                        if (StringUtils.isBlank(pv1.getPatientType().getValue())) { //PV1.18 - Tipo de Paciente
                            throw new HL7Exception("No se ha indicado el tipo de paciente (PV1-18: Patient Type)");
                        }
                    }
                } else {
                    throw new HL7Exception("No se ha indicado la clase de paciente (PV1-2: Patient Class)");
                }

                //PV1.19.1 - Codigo de Episodio
                if (StringUtils.isBlank(pv1.getVisitNumber().getIDNumber().getValue())) {
                    throw new HL7Exception("No se ha indicado el episodio del paciente (PV1.19: Visit Number)");
                }

                List<RAS_O17_ORDER> ras_o17_orders = ras_o17.getORDERAll();
                for (RAS_O17_ORDER ras_o17_order : ras_o17_orders) {
                    ORC orc = ras_o17_order.getORC();
                    TQ1 tq1 = ras_o17_order.getTIMING().getTQ1();
                    RXO rxo = ras_o17_order.getORDER_DETAIL().getRXO();
                    RXA rxa = ras_o17_order.getADMINISTRATION().getRXA();

                    //ORC.21.10 - OrganizationIdentifier
                    if (StringUtils
                            .isBlank(orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue())) { //ORC.21.10
                        throw new HL7Exception(
                                "No se ha indicado el centro de origen (ORC-21.10: OrganizationIdentifier)");
                    } else {
                        cod_centro = orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue();
                    }

                    //ORC.2.1 - Codigo de Prescripcion
                    if (StringUtils.isBlank(orc.getPlacerOrderNumber().getEntityIdentifier().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado el identificador de la prescripcion (ORC-2.1: Placer Order Number)");
                    }

                    //ORC.3.1 - Codigo de Administracion
                    if (StringUtils.isBlank(orc.getFillerOrderNumber().getEntityIdentifier().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado el identificador de la administracion (ORC-3.1: Filler Order Number)");
                    }

                    //ORC.10 - Medico Prescriptor
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getIDNumber().getValue())) { //ORC.10.1
                        throw new HL7Exception(
                                "No se ha indicado el codigo del medico prescriptor (ORC-10.1: Entered By)");
                    }
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getGivenName().getValue())) { //ORC.10.3
                        throw new HL7Exception(
                                "No se ha indicado el nombre del medico prescriptor (ORC-10.3: Entered By)");
                    }
                    if (StringUtils.isBlank(orc.getEnteredBy(0).getFamilyName().getSurname().getValue())) { //ORC.10.2.1
                        throw new HL7Exception(
                                "No se ha indicado el apellido del medico prescriptor (ORC-10.2.1: Entered By)");
                    }

                    //TQ1.7 - Fecha de Inicio de la Prescripcion
                    if (StringUtils.isBlank(tq1.getStartDateTime().getTime().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado la fecha de inicio de la prescripcion (TQ1-7: Start date/time)");
                    }

                    //RXA.3 - Fecha de la Administracion
                    if (StringUtils.isBlank(rxa.getDateTimeStartOfAdministration().getTime().getValue())) {
                        throw new HL7Exception(
                                "No se ha indicado la fecha de la adminsitracion (RXA-3: Start date/time)");
                    }

                    //RXA.5 - Marca
                    if (StringUtils.isBlank(rxa.getAdministeredCode().getIdentifier().getValue())) { //RXA.5.1
                        throw new HL7Exception(
                                "No se ha indicado el codigo nacional de la marca (RXA-5.1: AdministeredCode)");
                    }

                    //RXA.6 - Dosis Administrada en Forma Farmaceutica
                    if (StringUtils.isNotBlank(rxa.getAdministeredAmount().getValue())) { //RXA.6
                        try {
                            NumberUtils.createDouble(rxa.getAdministeredAmount().getValue());
                        } catch (Exception e) {
                            throw new HL7Exception("La dosis administrada no es correcta ["
                                    + rxa.getAdministeredAmount().getValue()
                                    + "] (ZRA-6: Dosis Administrada en Forma Farmaceutica)");
                        }
                    } else {
                        throw new HL7Exception(
                                "No se ha indicado dosis administrada (RXA-6: Dosis Administrada en Forma Farmaceutica)");
                    }

                    //RXO.2 - Dosis Prescrita en Unidad de Medida
                    if (StringUtils.isNotBlank(rxo.getRequestedGiveAmountMinimum().getValue())) { //RXO.2
                        try {
                            NumberUtils.createDouble(rxo.getRequestedGiveAmountMinimum().getValue());
                        } catch (Exception e) {
                            throw new HL7Exception("La dosis prescrita no es correcta ["
                                    + rxo.getRequestedGiveAmountMinimum().getValue()
                                    + "] (RXO-2: Dosis Prescrita en Unidad de Medida)");
                        }
                    } else {
                        throw new HL7Exception(
                                "No se ha indicado dosis prescrita (RXO-2: Dosis Prescrita en Unidad de Medida)");
                    }
                }
            } else {
                throw new HL7Exception("No se reconoce el tipo de mensaje (MSH.9 - Message Type)");
            }

            // Validacion del codigo de centro
            Centros centros = new Centros();
            centros.setCodCentro(cod_centro);
            try {
                centros = centrosService.findByCodCentro(centros);
            } catch (Exception e) {
                throw new HL7Exception(
                        "No se reconoce el codigo de centro " + cod_centro + " (" + e.getMessage() + ")");
            }

            logger.debug("     Almacenando el mensaje en BUZON_IN");
            BuzonIn buzonIn = new BuzonIn();
            buzonIn.setCentros(centros);
            buzonIn.setIdMensaje(msh.getMessageControlID().getValue()); //MSH.10
            buzonIn.setMensaje(message);
            buzonIn.setFechaIn(new Date());
            buzonIn.setEstado(AbstractIntegracionEntity.MENSAJE_NO_PROCESADO);
            buzonIn.setTipo(hl7message.getName());
            buzonInService.save(buzonIn);
            logger.debug("     Mensaje almacenado en BUZON_IN correctamente");

            ack = parser.generateACK(hl7message);
        } catch (Exception e) {
            try {
                logger.error("SE HAN PRODUCIDO ERRORES: " + e.toString());
                if (e.getCause() != null && e.getCause().getClass() == ConstraintViolationException.class) {
                    ack = parser.generateNACK(hl7message,
                            "El mensaje con MSH.10: "
                                    + ((MSH) hl7message.get("MSH")).getMessageControlID().getValue()
                                    + " ya se encuentra en el sistema");
                } else {
                    ack = parser.generateNACK(hl7message, e.getMessage());
                }
            } catch (Exception ex) {
                logger.error("SE HAN PRODUCIDO ERRORES: " + ex.toString());
                ack = parser.generateNACK(hl7message, ex.getMessage() != null ? ex.getMessage() : ex.toString());
            }
        }

        //Generar la respuesta
        String response;
        try {
            response = ack.encode();
        } catch (Exception e) {

            logger.error("No se ha podido generar la respuesta: " + e.toString() + "\rGenerando respuesta tipo");
            response = "MSH|^~\\&|MPR|mpr-ws|||"
                    + DateFormatUtils.formatUTC(System.currentTimeMillis(), "yyyyMMddHHmmss") + "||ACK|"
                    + System.currentTimeMillis() + "|P|2.5\r" + "MSA|AE\r"
                    + "ERR||||E|||NO SE HA PODIDO GENERAR UNA RESPUESTA: " + e.getMessage() != null ? e.getMessage()
                            : e.toString() + "\r";
        }

        logger.debug("     Respuesta a generar: ");
        logger.debug(response);
        logger.info("RECEPCION DEL MENSAJE FINALIZADA");

        return new ResponseEntity(response, HttpStatus.OK);
    }
}