Example usage for org.apache.commons.lang3.math NumberUtils createInteger

List of usage examples for org.apache.commons.lang3.math NumberUtils createInteger

Introduction

In this page you can find the example usage for org.apache.commons.lang3.math NumberUtils createInteger.

Prototype

public static Integer createInteger(final String str) 

Source Link

Document

Convert a String to a Integer, handling hex (0xhhhh) and octal (0dddd) notations.

Usage

From source file:de.micromata.genome.gwiki.plugin.rogmp3_1_0.Mp3Stats.java

public static void genStatistics(Mp3Db db, XmlElement node) {
    DecimalFormat df = new DecimalFormat("#,###");
    node.add(Html.p(code("Komponisten: " + df.format(db.composers.table.size()))));
    List<Media> ml = db.getMedia();
    int cdc = 0;//from w  ww.j  a v a 2s  .co m
    for (Media m : ml) {
        String mc = m.get(Media.MEDIACOUNT);
        if (StringUtils.isBlank(mc) == true) {
            ++cdc;
            continue;
        }
        try {
            cdc += NumberUtils.createInteger(mc);
        } catch (NumberFormatException ex) {
            ++cdc;
        }
    }
    int tcest = 36000;
    node.add(Html.p(code("Medien: " + df.format(ml.size()) + ", single: " + df.format(cdc))));
    node.add(Html.p(code("Titel: " + df.format(db.title.table.size()))));
    node.add(Html.p(code("<i>Only Parts with trackinfo</i>:")));
    double factor = (double) tcest / (double) db.tracks.table.size();

    node.add(Html.p(code("Tracks: " + df.format(db.tracks.table.size()))));
    long timesec = 0;
    long sizebytes = 0;
    for (String[] td : db.tracks.table) {
        Track track = new Track(db, td);
        timesec += track.getTime();
        sizebytes += track.getSize();
    }
    long esttimesec = (long) (factor * timesec);
    SimpleDateFormat sd = new SimpleDateFormat("MM-dd HH:mm:ss");
    String dur = sd.format(new Date(timesec * 1000));
    String esdur = sd.format(new Date(esttimesec * 1000));
    String size = df.format(sizebytes);

    node.add(Html.p(code("Total time: " + dur + ", " + df.format((int) (timesec / 3600)) + " hours")));
    node.add(Html.p(code("Total size: " + size + " (Parts)")));

    node.add(Html.p(code("Orchester: " + df.format(db.orchesters.table.size()))));
    node.add(Html.p(code("Intepreten: " + df.format(db.interprets.table.size()))));
}

From source file:io.cloudslang.content.utils.NumberUtilities.java

/**
 * Given an integer string, it checks if it's a valid integer (based on apaches NumberUtils.createInteger)
 *
 * @param integerStr the integer string to check
 * @return true if it's valid, otherwise false
 *///from w  ww . j a  va2  s  .c o  m
public static boolean isValidInt(@Nullable final String integerStr) {
    if (StringUtils.isBlank(integerStr)) {
        return false;
    }
    final String stripedInteger = StringUtils.strip(integerStr);
    try {
        NumberUtils.createInteger(stripedInteger);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

From source file:com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.JsonRenderedValueConverter.java

@Override
public Object convertRenderedValue(String rendered) {
    if (NumberUtils.isNumber(rendered)) {
        if (rendered.contains(".")) {
            return NumberUtils.createDouble(rendered);
        }//from   w w w .java 2  s.co  m
        try {
            return NumberUtils.createInteger(rendered);
        } catch (NumberFormatException ignored) {
            return NumberUtils.createLong(rendered);
        }
    } else if (rendered.equals("true") || rendered.equals("false")) {
        return Boolean.parseBoolean(rendered);
    } else if (rendered.startsWith("{{") || (!rendered.startsWith("{") && !rendered.startsWith("["))) {
        return rendered;
    }

    JsonNode node;
    try {
        node = pipelineTemplateObjectMapper.readTree(rendered);
    } catch (IOException e) {
        throw new TemplateRenderException("template produced invalid json", e);
    }

    try {
        if (node.isArray()) {
            return pipelineTemplateObjectMapper.readValue(rendered, Collection.class);
        }
        if (node.isObject()) {
            return pipelineTemplateObjectMapper.readValue(rendered, HashMap.class);
        }
        if (node.isBoolean()) {
            return Boolean.parseBoolean(node.asText());
        }
        if (node.isDouble()) {
            return node.doubleValue();
        }
        if (node.canConvertToInt()) {
            return node.intValue();
        }
        if (node.canConvertToLong()) {
            return node.longValue();
        }
        if (node.isTextual()) {
            return node.textValue();
        }
        if (node.isNull()) {
            return null;
        }
    } catch (IOException e) {
        throw new TemplateRenderException("template produced invalid json", e);
    }

    throw new TemplateRenderException("unknown rendered object type");
}

From source file:net.siegmar.japtproxy.misc.Configuration.java

/**
 * Initialize the configuration with the given config file.
 *
 * @param configFile the config file.//from ww  w  .  j  av a 2s .c  o  m
 * @throws InitializationException is thrown if the configuration is erroneous.
 */
public Configuration(final File configFile) throws InitializationException {
    try {
        final SAXBuilder sax = new SAXBuilder();
        final Document doc = sax.build(configFile);
        final Element rootElement = doc.getRootElement();

        cacheDir = new File(rootElement.getChildTextTrim("cache-dir"));
        httpProxy = rootElement.getChildTextTrim("http-proxy");

        final String maxVersionsString = rootElement.getChildTextTrim("max-versions");

        maxVersions = NumberUtils.createInteger(maxVersionsString);

        // support remap definitions
        // Syntax in config file:
        /*
        <remaps>
            <remap from="sourcehost" to="targethost"/>
        </remaps>
        */

        final List<Element> remapElements = rootElement.getChild("remaps").getChildren();

        for (final Element e : remapElements) {
            final String from = e.getAttributeValue("from");
            final String to = e.getAttributeValue("to");

            if (from == null || to == null) {
                LOG.debug("from or to missing from remap config element");
                throw new InitializationException(
                        "Error reading configuration. Remap does not contain from and/or to attribute");
            }

            if (remaps.containsKey(from)) {
                LOG.debug("Mapping for remap {} already present in config file", from);
                throw new InitializationException(
                        "Error reading configuration. Duplicate remap config for from: " + from);
            }

            LOG.debug("Added remap: {} -> {}", from, to);
            remaps.put(from, to);
        }

        /*
                    final List<Element> backends = rootElement.getChild("backends").getChildren();
                
                    // disable backend config
                
                
                    for (final Element e : backends) {
        final List<Element> confUrls = e.getChildren();
                
        if (confUrls == null || confUrls.isEmpty()) {
            continue;
        }
                
        final String name = e.getAttributeValue("name");
                
        final String type = e.getAttributeValue("type");
        if (type == null) {
            throw new InitializationException("type attribute is missing for backend '" + name + "'");
        }
                
        final String dir = e.getAttributeValue("dir");
                
        final Backend backend = new Backend(BackendType.valueOf(type.toUpperCase(Locale.ENGLISH)));
        final File backendDirectory = new File(cacheDir, StringUtils.defaultIfEmpty(dir, name));
                
        FileUtils.forceMkdir(backendDirectory);
                
        backend.setDirectory(backendDirectory);
                
        for (final Element confUrl : confUrls) {
            backend.addUrl(new URL(confUrl.getTextTrim()));
        }
                
        backendSystems.put(name, backend);
                    }
        */
    } catch (final IOException | JDOMException e) {
        throw new InitializationException("Error reading configuration", e);
    }

    LOG.debug("Initialized configuration: {}", this);
}

From source file:com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.HandlebarsRenderer.java

@Override
public Object renderGraph(String template, RenderContext context) {
    String rendered = render(template, context);

    // Short-circuit primitive values.
    // TODO rz - having trouble getting jackson to parse primitive values outside of unit tests
    if (NumberUtils.isNumber(rendered)) {
        if (rendered.contains(".")) {
            return NumberUtils.createDouble(rendered);
        }//from w ww.ja v  a 2s  .  co  m
        try {
            return NumberUtils.createInteger(rendered);
        } catch (NumberFormatException ignored) {
            return NumberUtils.createLong(rendered);
        }
    } else if (rendered.equals("true") || rendered.equals("false")) {
        return Boolean.parseBoolean(rendered);
    } else if (!rendered.startsWith("{") && !rendered.startsWith("[")) {
        return rendered;
    }

    JsonNode node;
    try {
        node = pipelineTemplateObjectMapper.readTree(rendered);
    } catch (IOException e) {
        throw new TemplateRenderException("template produced invalid json", e);
    }

    try {
        if (node.isArray()) {
            return pipelineTemplateObjectMapper.readValue(rendered, Collection.class);
        }
        if (node.isObject()) {
            return pipelineTemplateObjectMapper.readValue(rendered, HashMap.class);
        }
        if (node.isBoolean()) {
            return Boolean.parseBoolean(node.asText());
        }
        if (node.isDouble()) {
            return node.doubleValue();
        }
        if (node.canConvertToInt()) {
            return node.intValue();
        }
        if (node.canConvertToLong()) {
            return node.longValue();
        }
        if (node.isTextual()) {
            return node.textValue();
        }
        if (node.isNull()) {
            return null;
        }
    } catch (IOException e) {
        throw new TemplateRenderException("template produced invalid json", e);
    }

    throw new TemplateRenderException("unknown rendered object type");
}

From source file:io.cloudslang.content.utils.NumberUtilities.java

/**
 * Given an integer string if it's a valid int (see isValidInt) it converts it into an integer otherwise it throws an exception
 *
 * @param integerStr the integer to convert
 * @return the integer value of the integerStr
 * @throws IllegalArgumentException if the passed integer string is not a valid integer
 *///from   w  ww .j  a  va2s.  co m
public static int toInteger(@Nullable final String integerStr) {
    if (!isValidInt(integerStr)) {
        throw new IllegalArgumentException(
                integerStr + ExceptionValues.EXCEPTION_DELIMITER + ExceptionValues.INVALID_INTEGER_VALUE);
    }
    final String stripedInteger = StringUtils.strip(integerStr);
    return NumberUtils.createInteger(stripedInteger);
}

From source file:com.dominion.salud.mpr.ws.rest.MPRMessagesRESTHandlerService.java

@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);/*from www.j a v  a2  s .c  om*/

    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);
}

From source file:com.dominion.salud.mpr.negocio.service.tratamientos.impl.PrescripcionesServiceImpl.java

/**
 *
 * @param message/*from   ww  w . j a v  a 2  s.  c o m*/
 * @throws Exception
 */
@Override
@Transactional(noRollbackFor = { NoResultException.class })
public void processMessage(String message) throws Exception {
    logger.info("INICIANDO EL PROCESADO DEL MOVIMIENTO ENTRANTE");
    logger.info(message);

    //Resultado final del proceso
    List<String> resultado = new ArrayList<>();

    try {
        ZMP_O09 hl7message = (ZMP_O09) new ER7Parser().parse(message);
        PID pid = hl7message.getPATIENT().getPID();
        PV1 pv1 = hl7message.getPATIENT().getPATIENT_VISIT().getPV1();

        List<ZMP_O09_ORDER> zmp_o09_orders = hl7message.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 - Centro
            logger.debug("     Procesando datos del CENTRO ("
                    + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ") "
                    + orc.getOrderingFacilityName(0).getOrganizationName().getValue());
            Centros centros = new Centros();
            centros.setCodCentro(orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue()); //ORC.21.10
            try {
                centros = centrosService.findByCodCentro(centros);
                logger.debug("          ORC.21.10 - Centro: " + centros.toString());
            } catch (NoResultException nre) {
                logger.error(
                        "          No se puede procesar el movimiento sin EQUIVALENCIA para el campo ORC.21.10 - CENTRO ("
                                + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ")");
                resultado.add("No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: CENTRO ("
                        + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ")");
            }

            //PID.3 - Identificadores del paciente (NHC) y (CIPA)
            Integer nhc = null;
            String cipa = null;
            logger.debug("     Procesando el campo PID.3 - Identificadores del Paciente");
            for (int i = 0; i < pid.getPatientIdentifierList().length; i++) { // PID.3 - PatientIdentifierList
                if (StringUtils.equalsIgnoreCase(
                        pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "PI")) {
                    try {
                        nhc = NumberUtils
                                .createInteger(pid.getPatientIdentifierList(i).getIDNumber().getValue());
                        logger.debug("               PID.3(PI): " + nhc);
                    } catch (Exception e) {
                        logger.warn("El campo PID.3(PI) - NHC ("
                                + pid.getPatientIdentifierList(i).getIDNumber().getValue()
                                + ") no es correcto");
                    }
                } else if (StringUtils.equalsIgnoreCase(
                        pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "CIPA")) {
                    if (StringUtils.isNotBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                        cipa = pid.getPatientIdentifierList(i).getIDNumber().getValue();
                        logger.debug("               PID.3(CIPA): " + cipa);
                    }
                }
            }

            //PID.5 - Paciente
            logger.debug("     Procesando datos del PACIENTE ("
                    + pid.getPatientName(0).getFamilyName().getSurname().getValue() + " "
                    + pid.getMotherSMaidenName(0).getFamilyName().getSurname().getValue() + ", "
                    + pid.getPatientName(0).getGivenName().getValue() + ")");
            Pacientes pacientes = new Pacientes();
            pacientes.setCipa(cipa);
            pacientes.setTxtNombre(pid.getPatientName(0).getGivenName().getValue()); //PID.5.2
            pacientes.setTxtApellido1(pid.getPatientName(0).getFamilyName().getSurname().getValue()); //PID.5.1.1
            pacientes.setTxtApellido2(pid.getMotherSMaidenName(0).getFamilyName().getSurname().getValue()); //PID.6.1.1
            pacientes.setFechaNac(pid.getDateTimeOfBirth().getTime().getValueAsDate()); //PID.7.1
            logger.debug("          PID.5 - Paciente: " + pacientes.toString());

            //PID.8 - Sexo
            logger.debug("     Procesando datos del SEXO (" + pid.getAdministrativeSex().getValue() + ")");
            SexosExt sexosExt = new SexosExt();
            try {
                sexosExt.setCentros(centros);
                sexosExt.setCodSexoExt(pid.getAdministrativeSex().getValue()); //PID.8
                sexosExt.setTxtSexoExt(pid.getAdministrativeSex().getValue()); //PID.8
                sexosExt = sexosExtService.traducirEquivalencia(sexosExt);
                logger.debug("          PID.8 - Sexo: " + sexosExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(pid.getAdministrativeSex().getValue())) {
                    logger.warn("          No se ha encontrado EQUIVALENCIA para el CAMPO PID.8 - SEXO ("
                            + pid.getAdministrativeSex().getValue() + ")");
                } else {
                    logger.warn("          No se ha indicado INFORMACION para el CAMPO PID.8 - SEXO ("
                            + pid.getAdministrativeSex().getValue() + ")");
                }
            }

            //Datos del Episodio
            Episodios episodios = new Episodios();
            //PV1.2 - Clase de Paciente
            logger.debug(
                    "     Procesando datos de la CLASE DE PACIENTE (" + pv1.getPatientClass().getValue() + ")"); //PV1.2
            if (StringUtils.isNotBlank(pv1.getPatientClass().getValue())) {
                if (StringUtils.equals(pv1.getPatientClass().getValue(), "O")) { //Outpatient
                    //PV1.18 - Tipo de Paciente
                    logger.debug("          Procesando datos del TIPO DE PACIENTE ("
                            + pv1.getPatientType().getValue() + ")"); //PV1.18
                    if (StringUtils.isNotBlank(pv1.getPatientType().getValue())) {
                        episodios.setAmbito(pv1.getPatientType().getValue());
                    } else {
                        logger.error(
                                "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.18 - TIPO DE PACIENTE ("
                                        + pv1.getPatientType().getValue() + ")");
                        resultado.add(
                                "No se puede procesar el movimiento sin INFORMACION en el CAMPO: TIPO DE PACIENTE");
                    }
                } else {
                    episodios.setAmbito("H");
                }
                logger.debug("          PV1.2 - Clase de Paciente y PV1.18 - Tipo de Paciente: "
                        + episodios.getAmbito());
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.2 - CLASE DE PACIENTE ("
                                + pv1.getPatientClass().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CLASE DE PACIENTE");
            }

            //PV1.19.1 - Codigo de Episodio
            logger.debug("     Procesando datos del CODIGO DE EPISODIO ("
                    + pv1.getVisitNumber().getIDNumber().getValue() + ")"); //PV1.19.1
            if (StringUtils.isNotBlank(pv1.getVisitNumber().getIDNumber().getValue())) {
                episodios.setCodEpisodio(pv1.getVisitNumber().getIDNumber().getValue());
                logger.debug("          PV1.19.1 - Codigo de Episodio: " + episodios.getCodEpisodio());
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.19.1 - CODIGO DE EPISODIO ("
                                + pv1.getVisitNumber().getIDNumber().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE EPISODIO");
            }

            //ORC.2.1 - Codigo de Prescripcion
            String cod_prescripcion = null;
            logger.debug("     Procesando CODIGO DE PRESCRIPCION ("
                    + orc.getPlacerOrderNumber().getEntityIdentifier().getValue() + ")"); //ORC.2.1
            if (StringUtils.isNotBlank(orc.getPlacerOrderNumber().getEntityIdentifier().getValue())) {
                cod_prescripcion = orc.getPlacerOrderNumber().getEntityIdentifier().getValue();
                logger.debug("          ORC.2.1 - Codigo de Prescripcion: " + cod_prescripcion);
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO ORC.2.1 - CODIGO DE PRESCRIPCION ("
                                + orc.getPlacerOrderNumber().getEntityIdentifier().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE PRESCRIPCION");
            }

            //ORC.10 - Medico Prescriptor
            logger.debug("     Procesando datos del MEDICO PRESCRIPTOR ("
                    + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                    + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                    + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                    + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof().getValue());
            Medicos medicos = new Medicos();
            medicos.setCodMedico(orc.getEnteredBy(0).getIDNumber().getValue()); //ORC.10.1
            medicos.setTxtNombre(orc.getEnteredBy(0).getGivenName().getValue()); //ORC.10.3
            medicos.setTxtApellido1(orc.getEnteredBy(0).getFamilyName().getSurname().getValue()); //ORC.10.2.1
            medicos.setTxtApellido2(
                    orc.getEnteredBy(0).getSecondAndFurtherGivenNamesOrInitialsThereof().getValue()); //ORC.10.4
            medicos = medicosService.findByCodMedicoAndInsert(medicos);
            if (medicos != null) {
                logger.debug("          ORC.10 - Medico Prescriptor: " + medicos.toString());
            } else {
                logger.error(
                        "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: ORC.10 - MEDICO PRESCRIPTOR ("
                                + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                                + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                                + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                                + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof()
                                        .getValue());
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: MEDICO PRESCRIPTOR ("
                                + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                                + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                                + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                                + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof()
                                        .getValue());
            }

            //TQ1.7 - Fecha de Inicio de la Prescripcion
            Date fecha_ini_prescripcion = null;
            logger.debug("     Procesando FECHA DE INICIO DE LA PRESCRIPCION ("
                    + tq1.getStartDateTime().getTime().getValue() + ")"); //TQ1.7
            if (StringUtils.isNotBlank(tq1.getStartDateTime().getTime().getValue())
                    && tq1.getStartDateTime().getTime().getValueAsDate() != null) {
                fecha_ini_prescripcion = tq1.getStartDateTime().getTime().getValueAsDate();
                logger.debug("          TQ1.7 - Fecha de Inicio de la Prescripcion: " + fecha_ini_prescripcion);
            } else {
                logger.error(
                        "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: TQ1.7 - FECHA DE INICIO DE LA PRESCRIPCION ("
                                + tq1.getStartDateTime().getTime().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: FECHA DE INICIO DE LA PRESCRIPCION ("
                                + tq1.getStartDateTime().getTime().getValue() + ")");
            }

            //TQ1.8 - Fecha Fin de la Prescripcion
            Date fecha_fin_prescripcion = null;
            logger.debug("     Procesando FECHA DE FIN DE LA PRESCRIPCION ("
                    + tq1.getEndDateTime().getTime().getValue() + ")"); //TQ1.8
            if (StringUtils.isNotBlank(tq1.getEndDateTime().getTime().getValue())
                    && tq1.getEndDateTime().getTime().getValueAsDate() != null) {
                fecha_fin_prescripcion = tq1.getEndDateTime().getTime().getValueAsDate();
                logger.debug("          TQ1.8 - Fecha de Fin de la Prescripcion: " + fecha_fin_prescripcion);
            } else {
                logger.error(
                        "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: TQ1.8 - FECHA FIN DE LA PRESCRIPCION ("
                                + tq1.getEndDateTime().getTime().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: FECHA FIN DE LA PRESCRIPCION ("
                                + tq1.getEndDateTime().getTime().getValue() + ")");
            }

            //RXC.2 - Marca
            logger.debug("     Procesando de la MARCA (" + rxc.getComponentCode().getIdentifier().getValue()
                    + ") " + rxc.getComponentCode().getText().getValue());
            Marcas marcas = new Marcas();
            marcas.setCodNac(rxc.getComponentCode().getIdentifier().getValue()); //RXC.2.1
            marcas.setTxtMarca(rxc.getComponentCode().getText().getValue()); //RXC.2.2
            marcas = marcasService.findByCodNacAndInsert(marcas);
            if (marcas != null) {
                logger.debug("          RXC.2 - Marca: " + marcas.toString());
            } else {
                logger.error(
                        "               No se puede procesar el movimiento sin INFORMACION en el campo RXC.2 - MARCA ("
                                + rxc.getComponentCode().getIdentifier().getValue() + ") "
                                + rxc.getComponentCode().getText().getValue());
                resultado.add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: MARCA ("
                        + rxc.getComponentCode().getIdentifier().getValue() + ") "
                        + rxc.getComponentCode().getText().getValue());
            }

            //Z01.9 - Dosis Prescrita en Unidad de Medida
            Double dosis_prescrita = null;
            logger.debug(
                    "     Procesando datos de la DOSIS PRESCRITA (" + z01.getDosisPrescrita().getValue() + ")"); //Z01.9
            if (StringUtils.isNotBlank(z01.getDosisPrescrita().getValue())
                    && NumberUtils.isNumber(z01.getDosisPrescrita().getValue())) {
                try {
                    dosis_prescrita = NumberUtils.createDouble(z01.getDosisPrescrita().getValue());
                    logger.debug("          Z01.9 - Dosis Prescrita: " + dosis_prescrita);
                } catch (Exception e) {
                    logger.error(
                            "          No se puede procesar el movimiento porque la INFORMACION en el campo Z01.9 - DOSIS PRESCRITA ("
                                    + z01.getDosisPrescrita().getValue() + ") NO es correcta");
                    resultado.add(
                            "No se puede procesar el movimiento porque la INFORMACION en el CAMPO: DOSIS PRESCRITA ("
                                    + z01.getDosisPrescrita().getValue() + ") NO es correcta");
                }
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin datos en el campo Z01.9 - Dosis Prescrita ("
                                + z01.getDosisPrescrita().getValue() + ")");
                resultado
                        .add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: Dosis Prescrita ("
                                + z01.getDosisPrescrita().getValue() + ")");
            }

            //Z01.10 - Unidad de Medida de la Dosis Prescrita
            logger.debug("     Procesando datos de la UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                    + z01.getUnidMedDosisPrescrita().getIdentifier().getValue() + ") "
                    + z01.getUnidMedDosisPrescrita().getText().getValue());
            UnidMedExt unidMedExt = new UnidMedExt();
            try {
                unidMedExt.setCentros(centros);
                unidMedExt.setCodUnidMedExt(z01.getUnidMedDosisPrescrita().getIdentifier().getValue()); //Z01.10.1
                unidMedExt.setTxtUnidMedExt(z01.getUnidMedDosisPrescrita().getText().getValue()); //Z01.10.2
                unidMedExt = unidMedExtService.traducirEquivalenciaAndInsert(unidMedExt);
                logger.debug(
                        "          Z01.10 - Unidad de Medida de la Dosis Prescrita: " + unidMedExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(z01.getUnidMedDosisPrescrita().getIdentifier().getValue())) {
                    logger.warn(
                            "               No se ha indicado INFORMACION para el CAMPO Z01.10 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                    + z01.getUnidMedDosisPrescrita().getIdentifier().getValue() + ") "
                                    + z01.getUnidMedDosisPrescrita().getText().getValue());
                } else {
                    logger.warn(
                            "               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.10 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                    + z01.getUnidMedDosisPrescrita().getIdentifier().getValue() + ") "
                                    + z01.getUnidMedDosisPrescrita().getText().getValue());
                }
            }

            //Z01.13 - Secuencias
            logger.debug("     Procesando de la SECUENCIA (" + z01.getSecuencia().getIdentifier().getValue()
                    + ") " + z01.getSecuencia().getText().getValue());
            SecuenciasExt secuenciasExt = new SecuenciasExt();
            try {
                secuenciasExt.setCentros(centros);
                secuenciasExt.setCodSecuenciaExt(z01.getSecuencia().getIdentifier().getValue()); //Z01.13.1
                secuenciasExt.setTxtSecuenciaExt(z01.getSecuencia().getText().getValue()); //Z01.13.2
                secuenciasExt = secuenciasExtService.traducirEquivalenciaAndInsert(secuenciasExt);
                logger.debug("          Z01.13 - Secuencia: " + secuenciasExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(z01.getSecuencia().getIdentifier().getValue())) {
                    logger.warn(
                            "               No se ha indicado INFORMACION para el CAMPO Z01.13 - SECUENCIA ("
                                    + z01.getSecuencia().getIdentifier().getValue() + ") "
                                    + z01.getSecuencia().getText().getValue());
                } else {
                    logger.warn(
                            "               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.13 - SECUENCIA ("
                                    + z01.getSecuencia().getIdentifier().getValue() + ") "
                                    + z01.getSecuencia().getText().getValue());
                }
            }

            //Z01.14 - Pautas
            logger.debug("     Procesando de la PAUTA (" + z01.getPauta().getIdentifier().getValue() + ") "
                    + z01.getPauta().getText().getValue());
            PautasExt pautasExt = new PautasExt();
            try {
                pautasExt.setCentros(centros);
                pautasExt.setCodPautaExt(z01.getPauta().getIdentifier().getValue()); //Z01.14.1
                pautasExt.setTxtPautaExt(z01.getPauta().getText().getValue()); //Z01.14.2
                pautasExt = pautasExtService.traducirEquivalenciaAndInsert(pautasExt);
                logger.debug("          Z01.14 - Pauta: " + pautasExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(z01.getPauta().getIdentifier().getValue())) {
                    logger.warn("               No se ha indicado INFORMACION para el CAMPO Z01.14 - PAUTA ("
                            + z01.getPauta().getIdentifier().getValue() + ") "
                            + z01.getPauta().getText().getValue());
                } else {
                    logger.warn("               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.14 - PAUTA ("
                            + z01.getPauta().getIdentifier().getValue() + ") "
                            + z01.getPauta().getText().getValue());
                }
            }

            //Z01.16 - Razon Fin
            logger.debug("     Procesando la RAZON DE FIN DE TRATAMIENTO ("
                    + z01.getRazonFin().getIdentifier().getValue() + ") "
                    + z01.getRazonFin().getText().getValue());
            RazonFinExt razonFinExt = new RazonFinExt();
            try {
                razonFinExt.setCentros(centros);
                razonFinExt.setCodRazonFinExt(z01.getRazonFin().getIdentifier().getValue()); //Z01.16.1
                razonFinExt.setTxtRazonFinExt(z01.getRazonFin().getText().getValue()); //Z01.16.2
                razonFinExt = razonFinExtService.traducirEquivalenciaAndInsert(razonFinExt);
                logger.debug("          Z01.16 - Razon de Fin: " + razonFinExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(z01.getRazonFin().getIdentifier().getValue())) {
                    logger.warn(
                            "               No se ha indicado INFORMACION para el CAMPO Z01.16 - RAZON DE FIN DE TRATAMIENTO ("
                                    + z01.getRazonFin().getIdentifier().getValue() + ") "
                                    + z01.getRazonFin().getText().getValue());
                } else {
                    logger.warn(
                            "               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.16 - RAZON DE FIN DE TRATAMIENTO ("
                                    + z01.getRazonFin().getIdentifier().getValue() + ") "
                                    + z01.getRazonFin().getText().getValue());
                }
            }

            //RESULTADO GENERAL DEL PROCESADO DEL MOVIMIENTO
            String mensaje = "";
            if (!resultado.isEmpty()) {
                logger.error("RESULTADO GENERAL DEL PROCESADO: ");
                for (String linea : resultado) {
                    mensaje += "     - " + linea + "\n";
                }
                logger.error("     " + mensaje);
            }

            if (StringUtils.isNotBlank(mensaje)) {
                throw new Exception(mensaje);
            }
            logger.info("FINALIZANDO EL PROCESADO DEL MOVIMIENTO ENTRANTE ENTRANTE");

            //ALMACENAMIENTO DEL MOVIMIENTO
            logger.info("INICIANDO EL ALMACENAMIENTO DEL MOVIMIENTO ENTRANTE");

            //PACIENTE
            try {
                logger.debug("     Buscando PACIENTE por CIPA (" + pacientes.getCipa() + ")");
                pacientes = pacientesService.findByCIPA(pacientes);
            } catch (NoResultException nre) {
                logger.debug("          Almacenando datos del PACIENTE");
                pacientes.setSexos(sexosExt.getSexos());
                pacientes = pacientesService.save(pacientes);
            } finally {
                logger.debug("          Paciente: " + pacientes.toString());
            }

            //EPISODIO
            try {
                episodios.setNhc(nhc);
                episodios.setCentros(centros);
                episodios.setPacientes(pacientes);

                logger.debug("     Buscando EPISODIO por COD_EPISODIO (" + episodios.getCodEpisodio()
                        + "), NHC (" + episodios.getNhc() + "), PROGRAMA (" + episodios.getProgramas()
                        + "), CENTRO (" + episodios.getCentros() + ")");
                episodios = episodiosService.findByCodEpisodioNHCIdProgramaIdCentro(episodios);
            } catch (NoResultException nre) {
                logger.debug("          Almacenando datos del EPISODIO");
                episodios = episodiosService.save(episodios);
            } finally {
                logger.debug("          Episodio: " + episodios.toString());
            }

            //PRESCRIPCIONES
            logger.debug("     Almacenando datos de la PRESCRIPCION: (" + cod_prescripcion + ")");
            Prescripciones prescripciones = new Prescripciones();
            try {
                prescripciones.setCodPrescripcion(cod_prescripcion);
                logger.debug("          Buscando PRESCRIPCION por COD_PRESCRIPCION ("
                        + prescripciones.getCodPrescripcion() + ")");
                prescripciones = findByCodPrescripcion(prescripciones);

                logger.debug("          Actualizando PRESCRIPCION por COD_PRESCRIPCION ("
                        + prescripciones.getCodPrescripcion() + ")");
                prescripciones.setFechaFin(fecha_fin_prescripcion);
                prescripciones.setRazonFin(razonFinExt.getRazonFin());
                prescripciones = save(prescripciones);
            } catch (NoResultException nre) {
                Prescripciones prescripcionesOld = new Prescripciones();
                prescripcionesOld
                        .setCodPrescripcion(StringUtils.split(prescripciones.getCodPrescripcion(), "-")[0] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[1] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[2] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[3] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[4]);
                List<Prescripciones> prescripcioneses = findLikeCodPrescripcion(prescripcionesOld);
                for (Prescripciones prescripcionesUpd : prescripcioneses) {
                    if (StringUtils.equals(StringUtils.split(prescripcionesUpd.getCodPrescripcion(), "-")[7],
                            StringUtils.split(prescripciones.getCodPrescripcion(), "-")[7])) {
                        logger.debug("               Estableciendo fecha de fin en la prescripcion: "
                                + prescripcionesUpd.toString());
                        prescripcionesUpd.setFechaFin(new Date());
                        save(prescripcionesUpd);
                    }
                }

                prescripciones.setEpisodios(episodios);
                prescripciones.setMarcas(marcas);
                prescripciones.setMedicos(medicos);
                prescripciones.setDosis(dosis_prescrita);
                prescripciones.setFechaIni(fecha_ini_prescripcion);
                prescripciones.setFechaFin(fecha_fin_prescripcion);
                prescripciones.setRazonFin(razonFinExt.getRazonFin());
                prescripciones.setCodPrescripcion(cod_prescripcion);
                prescripciones.setPautas(pautasExt.getPautas());
                prescripciones.setRazonFin(razonFinExt.getRazonFin());
                prescripciones.setSecuencias(secuenciasExt.getSecuencias());
                prescripciones.setUnidMed(unidMedExt.getUnidMed());
                prescripciones = save(prescripciones);
            } finally {
                logger.debug("          Prescripcion: " + prescripciones.toString());
            }
            logger.info("FINALIZANDO EL ALMACENAMIENTO DEL MOVIMIENTO ENTRANTE");
        }
    } catch (Exception e) {
        throw new Exception("SE HAN PRODUCIDO ERRORES AL PROCESAR EL MOVIMIENTO: \n" + e.getMessage() != null
                ? e.getMessage()
                : e.toString());
    }
}

From source file:com.dominion.salud.mpr.negocio.service.tratamientos.impl.AdministracionesServiceImpl.java

@Override
@Transactional(noRollbackFor = { NoResultException.class })
public void processMessage(String message) throws Exception {
    logger.info("INICIANDO EL PROCESADO DEL MOVIMIENTO ENTRANTE");
    logger.info(message);/*from  www.ja va2 s. c o m*/

    //Resultado final del proceso
    List<String> resultado = new ArrayList<>();

    try {
        RAS_O17 hl7message = (RAS_O17) new ER7Parser().parse(message);

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

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

            //ORC.21.10 - Centro
            logger.debug("     Procesando datos del CENTRO ("
                    + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ") "
                    + orc.getOrderingFacilityName(0).getOrganizationName().getValue());
            Centros centros = new Centros();
            centros.setCodCentro(orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue()); //ORC.21.10
            try {
                centros = centrosService.findByCodCentro(centros);
                logger.debug("          ORC.21.10 - Centro: " + centros.toString());
            } catch (NoResultException nre) {
                logger.error(
                        "          No se puede procesar el movimiento sin EQUIVALENCIA para el campo ORC.21.10 - CENTRO ("
                                + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ")");
                resultado.add("No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: CENTRO ("
                        + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ")");
            }

            //PID.3 - Identificadores del paciente (NHC) y (CIPA)
            Integer nhc = null;
            String cipa = null;
            logger.debug("     Procesando el campo PID.3 - Identificadores del Paciente");
            for (int i = 0; i < pid.getPatientIdentifierList().length; i++) { // PID.3 - PatientIdentifierList
                if (StringUtils.equalsIgnoreCase(
                        pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "PI")) {
                    try {
                        nhc = NumberUtils
                                .createInteger(pid.getPatientIdentifierList(i).getIDNumber().getValue());
                        logger.debug("               PID.3(PI): " + nhc);
                    } catch (Exception e) {
                        logger.warn("El campo PID.3(PI) - NHC ("
                                + pid.getPatientIdentifierList(i).getIDNumber().getValue()
                                + ") no es correcto");
                    }
                } else if (StringUtils.equalsIgnoreCase(
                        pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "CIPA")) {
                    if (StringUtils.isNotBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                        cipa = pid.getPatientIdentifierList(i).getIDNumber().getValue();
                        logger.debug("               PID.3(CIPA): " + cipa);
                    }
                }
            }

            //PID.5 - Paciente
            logger.debug("     Procesando datos del PACIENTE ("
                    + pid.getPatientName(0).getFamilyName().getSurname().getValue() + " "
                    + pid.getMotherSMaidenName(0).getFamilyName().getSurname().getValue() + ", "
                    + pid.getPatientName(0).getGivenName().getValue() + ")");
            Pacientes pacientes = new Pacientes();
            pacientes.setCipa(cipa);
            pacientes.setTxtNombre(pid.getPatientName(0).getGivenName().getValue()); //PID.5.2
            pacientes.setTxtApellido1(pid.getPatientName(0).getFamilyName().getSurname().getValue()); //PID.5.1.1
            pacientes.setTxtApellido2(pid.getMotherSMaidenName(0).getFamilyName().getSurname().getValue()); //PID.6.1.1
            pacientes.setFechaNac(pid.getDateTimeOfBirth().getTime().getValueAsDate()); //PID.7.1
            logger.debug("          PID.5 - Paciente: " + pacientes.toString());

            //PID.8 - Sexo
            logger.debug("     Procesando datos del SEXO (" + pid.getAdministrativeSex().getValue() + ")");
            SexosExt sexosExt = new SexosExt();
            try {
                sexosExt.setCentros(centros);
                sexosExt.setCodSexoExt(pid.getAdministrativeSex().getValue()); //PID.8
                sexosExt.setTxtSexoExt(pid.getAdministrativeSex().getValue()); //PID.8
                sexosExt = sexosExtService.traducirEquivalencia(sexosExt);
                logger.debug("          PID.8 - Sexo: " + sexosExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(pid.getAdministrativeSex().getValue())) {
                    logger.warn("          No se ha encontrado EQUIVALENCIA para el CAMPO PID.8 - SEXO ("
                            + pid.getAdministrativeSex().getValue() + ")");
                } else {
                    logger.warn("          No se ha indicado INFORMACION para el CAMPO PID.8 - SEXO ("
                            + pid.getAdministrativeSex().getValue() + ")");
                }
            }

            //Datos del Episodio
            Episodios episodios = new Episodios();
            //PV1.2 - Clase de Paciente
            logger.debug(
                    "     Procesando datos de la CLASE DE PACIENTE (" + pv1.getPatientClass().getValue() + ")"); //PV1.2
            if (StringUtils.isNotBlank(pv1.getPatientClass().getValue())) {
                if (StringUtils.equals(pv1.getPatientClass().getValue(), "O")) { //Outpatient
                    //PV1.18 - Tipo de Paciente
                    logger.debug("          Procesando datos del TIPO DE PACIENTE ("
                            + pv1.getPatientType().getValue() + ")"); //PV1.18
                    if (StringUtils.isNotBlank(pv1.getPatientType().getValue())) {
                        episodios.setAmbito(pv1.getPatientType().getValue());
                    } else {
                        logger.error(
                                "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.18 - TIPO DE PACIENTE ("
                                        + pv1.getPatientType().getValue() + ")");
                        resultado.add(
                                "No se puede procesar el movimiento sin INFORMACION en el CAMPO: TIPO DE PACIENTE");
                    }
                } else {
                    episodios.setAmbito("H");
                }
                logger.debug("          PV1.2 - Clase de Paciente y PV1.18 - Tipo de Paciente: "
                        + episodios.getAmbito());
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.2 - CLASE DE PACIENTE ("
                                + pv1.getPatientClass().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CLASE DE PACIENTE");
            }

            //PV1.19.1 - Codigo de Episodio
            logger.debug("     Procesando datos del CODIGO DE EPISODIO ("
                    + pv1.getVisitNumber().getIDNumber().getValue() + ")"); //PV1.19.1
            if (StringUtils.isNotBlank(pv1.getVisitNumber().getIDNumber().getValue())) {
                episodios.setCodEpisodio(pv1.getVisitNumber().getIDNumber().getValue());
                logger.debug("          PV1.19.1 - Codigo de Episodio: " + episodios.getCodEpisodio());
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.19.1 - CODIGO DE EPISODIO ("
                                + pv1.getVisitNumber().getIDNumber().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE EPISODIO");
            }

            //ORC.2.1 - Codigo de Prescripcion
            String cod_prescripcion = null;
            logger.debug("     Procesando CODIGO DE PRESCRIPCION ("
                    + orc.getPlacerOrderNumber().getEntityIdentifier().getValue() + ")"); //ORC.2.1
            if (StringUtils.isNotBlank(orc.getPlacerOrderNumber().getEntityIdentifier().getValue())) {
                cod_prescripcion = orc.getPlacerOrderNumber().getEntityIdentifier().getValue();
                logger.debug("          ORC.2.1 - Codigo de Prescripcion: " + cod_prescripcion);
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO ORC.2.1 - CODIGO DE PRESCRIPCION ("
                                + orc.getPlacerOrderNumber().getEntityIdentifier().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE PRESCRIPCION");
            }

            //ORC.3.1 - Codigo de Administracion
            String cod_administracion = null;
            logger.debug("     Procesando CODIGO DE ADMINSTRACION ("
                    + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")"); //ORC.2.1
            if (StringUtils.isNotBlank(orc.getFillerOrderNumber().getEntityIdentifier().getValue())) {
                cod_administracion = orc.getFillerOrderNumber().getEntityIdentifier().getValue();
                logger.debug("          ORC.3.1 - Codigo de Administracion: " + cod_administracion);
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el campo ORC.3.1 - CODIGO DE ADMINSTRACION ("
                                + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE ADMINSTRACION ("
                                + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")");
            }

            //ORC.10 - Medico Prescriptor
            logger.debug("     Procesando datos del MEDICO PRESCRIPTOR ("
                    + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                    + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                    + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                    + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof().getValue());
            Medicos medicos = new Medicos();
            medicos.setCodMedico(orc.getEnteredBy(0).getIDNumber().getValue()); //ORC.10.1
            medicos.setTxtNombre(orc.getEnteredBy(0).getGivenName().getValue()); //ORC.10.3
            medicos.setTxtApellido1(orc.getEnteredBy(0).getFamilyName().getSurname().getValue()); //ORC.10.2.1
            medicos.setTxtApellido2(
                    orc.getEnteredBy(0).getSecondAndFurtherGivenNamesOrInitialsThereof().getValue()); //ORC.10.4
            medicos = medicosService.findByCodMedicoAndInsert(medicos);
            if (medicos != null) {
                logger.debug("          ORC.10 - Medico Prescriptor: " + medicos.toString());
            } else {
                logger.error(
                        "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: ORC.10 - MEDICO PRESCRIPTOR ("
                                + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                                + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                                + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                                + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof()
                                        .getValue());
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: MEDICO PRESCRIPTOR ("
                                + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                                + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                                + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                                + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof()
                                        .getValue());
            }

            //TQ1.7 - Fecha de Inicio de la Prescripcion
            Date fecha_ini_prescripcion = null;
            logger.debug("     Procesando FECHA DE INICIO DE LA PRESCRIPCION ("
                    + tq1.getStartDateTime().getTime().getValue() + ")"); //TQ1.7
            if (StringUtils.isNotBlank(tq1.getStartDateTime().getTime().getValue())
                    && tq1.getStartDateTime().getTime().getValueAsDate() != null) {
                fecha_ini_prescripcion = tq1.getStartDateTime().getTime().getValueAsDate();
                logger.debug("          TQ1.7 - Fecha de Inicio de la Prescripcion: " + fecha_ini_prescripcion);
            } else {
                logger.error(
                        "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: TQ1.7 - FECHA DE INICIO DE LA PRESCRIPCION ("
                                + tq1.getStartDateTime().getTime().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: FECHA DE INICIO DE LA PRESCRIPCION ("
                                + tq1.getStartDateTime().getTime().getValue() + ")");
            }

            //RXA.3 - Fecha de la Administracion
            Date fecha_administracion = null;
            logger.debug("     Procesando FECHA DE LA ADMINISTRACION ("
                    + rxa.getDateTimeStartOfAdministration().getTime().getValue() + ")"); //RXA.3
            if (StringUtils.isNotBlank(rxa.getDateTimeStartOfAdministration().getTime().getValue())
                    && rxa.getDateTimeStartOfAdministration().getTime().getValueAsDate() != null) {
                fecha_administracion = rxa.getDateTimeStartOfAdministration().getTime().getValueAsDate();
                logger.debug("          RXA.3 - Fecha de la Administracion: " + fecha_administracion);
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO RXD.3 - FECHA DE LA ADMINISTRACION ("
                                + rxa.getDateTimeStartOfAdministration().getTime().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: FECHA DE LA ADMINISTRACION ("
                                + rxa.getDateTimeStartOfAdministration().getTime().getValue() + ")");
            }

            //RXA.5 - Marca
            logger.debug("     Procesando de la MARCA (" + rxa.getAdministeredCode().getIdentifier().getValue()
                    + ") " + rxa.getAdministeredCode().getText().getValue());
            Marcas marcas = new Marcas();
            marcas.setCodNac(rxa.getAdministeredCode().getIdentifier().getValue()); //RXA.5.1
            marcas.setTxtMarca(rxa.getAdministeredCode().getText().getValue()); //RXA.5.2
            marcas = marcasService.findByCodNacAndInsert(marcas);
            if (marcas != null) {
                logger.debug("          RXA.5 - Marca: " + marcas.toString());
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO RXA.5 - MARCA ("
                                + rxa.getAdministeredCode().getIdentifier().getValue() + ") "
                                + rxa.getAdministeredCode().getText().getValue());
                resultado.add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: MARCA ("
                        + rxa.getAdministeredCode().getIdentifier().getValue() + ") "
                        + rxa.getAdministeredCode().getText().getValue());
            }

            //RXA.6 - Dosis Administrada en Forma Farmaceutica
            Double dosis_administrada = null;
            logger.debug("     Procesando datos de la DOSIS ADMINISTRADA ("
                    + rxa.getAdministeredAmount().getValue() + ")"); //RXA.6
            if (StringUtils.isNotBlank(rxa.getAdministeredAmount().getValue())
                    && NumberUtils.isNumber(rxa.getAdministeredAmount().getValue())) {
                try {
                    dosis_administrada = NumberUtils.createDouble(rxa.getAdministeredAmount().getValue());
                    logger.debug("          RXA.6 - Dosis Administrada: " + dosis_administrada);
                } catch (Exception e) {
                    logger.error(
                            "          No se puede procesar el movimiento porque la INFORMACION en el CAMPO RXA.6 - DOSIS ADMINISTRADA ("
                                    + rxa.getAdministeredAmount().getValue() + ") NO es correcta");
                    resultado.add(
                            "No se puede procesar el movimiento porque la INFORMACION en el CAMPO: DOSIS ADMINISTRADA ("
                                    + rxa.getAdministeredAmount().getValue() + ") NO es correcta");
                }
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO RXA.6 - Dosis Administrada ("
                                + rxa.getAdministeredAmount().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: Dosis Administrada ("
                                + rxa.getAdministeredAmount().getValue() + ")");
            }

            //RXA.7 - Forma Farmaceutica de la Dosis Administrada
            logger.debug("     Procesando la FORMA FARMACEUTICA DE LA DOSIS ADMINISTRADA ("
                    + rxa.getAdministeredUnits().getIdentifier().getValue() + ") "
                    + rxa.getAdministeredUnits().getText().getValue());
            FormasFarExt formasFarExt = new FormasFarExt();
            try {
                formasFarExt.setCentros(centros);
                formasFarExt.setCodFormaFarExt(rxa.getAdministeredUnits().getIdentifier().getValue()); //RXA.7.1
                formasFarExt.setTxtFormaFarExt(rxa.getAdministeredUnits().getText().getValue()); //RXA.7.2
                formasFarExt = formasFarExtService.traducirEquivalenciaAndInsert(formasFarExt);
                logger.debug("          RXA.7 - Forma Farmaceutica de la Dosis Administrada: "
                        + formasFarExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(rxa.getAdministeredUnits().getIdentifier().getValue())) {
                    logger.warn(
                            "               No se ha indicado INFORMACION para el CAMPO RXA.7 - FORMA FARMACEUTICA DE LA DOSIS ADMINISTRADA ("
                                    + rxa.getAdministeredUnits().getIdentifier().getValue() + ") "
                                    + rxa.getAdministeredUnits().getText().getValue());
                } else {
                    logger.warn(
                            "               No se ha encontrado EQUIVALENCIA para el CAMPO RXA.7 - FORMA FARMACEUTICA DE LA DOSIS ADMINISTRADA ("
                                    + rxa.getAdministeredUnits().getIdentifier().getValue() + ") "
                                    + rxa.getAdministeredUnits().getText().getValue());
                }
            }

            //RXA.9 - Pautas
            logger.debug(
                    "     Procesando de la PAUTA (" + rxa.getAdministrationNotes(0).getIdentifier().getValue()
                            + ") " + rxa.getAdministrationNotes(0).getText().getValue());
            PautasExt pautasExt = new PautasExt();
            try {
                pautasExt.setCentros(centros);
                pautasExt.setCodPautaExt(rxa.getAdministrationNotes(0).getIdentifier().getValue()); //RXA.9.1
                pautasExt.setTxtPautaExt(rxa.getAdministrationNotes(0).getText().getValue()); //RXA.9.2
                pautasExt = pautasExtService.traducirEquivalenciaAndInsert(pautasExt);
                logger.debug("          RXA.9 - Pauta: " + pautasExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(rxa.getAdministrationNotes(0).getIdentifier().getValue())) {
                    logger.warn("               No se ha indicado INFORMACION para el CAMPO RXA.9 - PAUTA ("
                            + rxa.getAdministrationNotes(0).getIdentifier().getValue() + ") "
                            + rxa.getAdministrationNotes(0).getText().getValue());
                } else {
                    logger.warn("               No se ha encontrado EQUIVALENCIA para el CAMPO RXA.9 - PAUTA ("
                            + rxa.getAdministrationNotes(0).getIdentifier().getValue() + ") "
                            + rxa.getAdministrationNotes(0).getText().getValue());
                }
            }

            //RXA.19 - Secuencias
            logger.debug("     Procesando de la SECUENCIA (" + rxa.getIndication(0).getIdentifier().getValue()
                    + ") " + rxa.getIndication(0).getText().getValue());
            SecuenciasExt secuenciasExt = new SecuenciasExt();
            try {
                secuenciasExt.setCentros(centros);
                secuenciasExt.setCodSecuenciaExt(rxa.getIndication(0).getIdentifier().getValue()); //RXA.19.1
                secuenciasExt.setTxtSecuenciaExt(rxa.getIndication(0).getText().getValue()); //RXA.19.2
                secuenciasExt = secuenciasExtService.traducirEquivalenciaAndInsert(secuenciasExt);
                logger.debug("          RXA.19 - Secuencia: " + secuenciasExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(rxa.getIndication(0).getIdentifier().getValue())) {
                    logger.warn(
                            "               No se ha indicado INFORMACION para el CAMPO RXA.19 - SECUENCIA ("
                                    + rxa.getIndication(0).getIdentifier().getValue() + ") "
                                    + rxa.getIndication(0).getText().getValue());
                } else {
                    logger.warn(
                            "               No se ha encontrado EQUIVALENCIA para el CAMPO RXA.19 - SECUENCIA ("
                                    + rxa.getIndication(0).getIdentifier().getValue() + ") "
                                    + rxa.getIndication(0).getText().getValue());
                }
            }

            //RXO.2 - Dosis Prescrita en Unidad de Medida
            Double dosis_prescrita = null;
            logger.debug("     Procesando datos de la DOSIS PRESCRITA ("
                    + rxo.getRequestedGiveAmountMinimum().getValue() + ")"); //RXO.2
            if (StringUtils.isNotBlank(rxo.getRequestedGiveAmountMinimum().getValue())
                    && NumberUtils.isNumber(rxo.getRequestedGiveAmountMinimum().getValue())) {
                try {
                    dosis_prescrita = NumberUtils.createDouble(rxo.getRequestedGiveAmountMinimum().getValue());
                    logger.debug("          RXO.2 - Dosis Prescrita: " + dosis_prescrita);
                } catch (Exception e) {
                    logger.error(
                            "          No se puede procesar el movimiento porque la INFORMACION en el campo RXO.2 - DOSIS PRESCRITA ("
                                    + rxo.getRequestedGiveAmountMinimum().getValue() + ") NO es correcta");
                    resultado.add(
                            "No se puede procesar el movimiento porque la INFORMACION en el CAMPO: DOSIS PRESCRITA ("
                                    + rxo.getRequestedGiveAmountMinimum().getValue() + ") NO es correcta");
                }
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin datos en el campo RXO.2 - DOSIS PRESCRITA ("
                                + rxo.getRequestedGiveAmountMinimum().getValue() + ")");
                resultado
                        .add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: DOSIS PRESCRITA ("
                                + rxo.getRequestedGiveAmountMinimum().getValue() + ")");
            }

            //RXO.4 - Unidad de Medida de la Dosis Prescrita
            logger.debug("     Procesando datos de la UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                    + rxo.getRequestedGiveUnits().getIdentifier().getValue() + ") "
                    + rxo.getRequestedGiveUnits().getText().getValue());
            UnidMedExt unidMedExt = new UnidMedExt();
            try {
                unidMedExt.setCentros(centros);
                unidMedExt.setCodUnidMedExt(rxo.getRequestedGiveUnits().getIdentifier().getValue()); //Z01.10.1
                unidMedExt.setTxtUnidMedExt(rxo.getRequestedGiveUnits().getText().getValue()); //Z01.10.2
                unidMedExt = unidMedExtService.traducirEquivalenciaAndInsert(unidMedExt);
                logger.debug(
                        "          RXO.4 - Unidad de Medida de la Dosis Prescrita: " + unidMedExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (StringUtils.isNotBlank(rxo.getRequestedGiveUnits().getIdentifier().getValue())) {
                    logger.warn(
                            "               No se ha indicado INFORMACION para el CAMPO RXO.4 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                    + rxo.getRequestedGiveUnits().getIdentifier().getValue() + ") "
                                    + rxo.getRequestedGiveUnits().getText().getValue());
                } else {
                    logger.warn(
                            "               No se ha encontrado EQUIVALENCIA para el CAMPO RXO.4 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                    + rxo.getRequestedGiveUnits().getIdentifier().getValue() + ") "
                                    + rxo.getRequestedGiveUnits().getText().getValue());
                }
            }

            //RESULTADO GENERAL DEL PROCESADO DEL MOVIMIENTO
            String mensaje = "";
            if (!resultado.isEmpty()) {
                logger.error("RESULTADO GENERAL DEL PROCESADO: ");
                for (String linea : resultado) {
                    mensaje += "     - " + linea + "\n";
                }
                logger.error("     " + mensaje);
            }

            if (StringUtils.isNotBlank(mensaje)) {
                throw new Exception(mensaje);
            }
            logger.info("FINALIZANDO EL PROCESADO DEL MOVIMIENTO ENTRANTE ENTRANTE");

            //ALMACENAMIENTO DEL MOVIMIENTO
            logger.info("INICIANDO EL ALMACENAMIENTO DEL MOVIMIENTO ENTRANTE");

            //PACIENTE
            try {
                logger.debug("     Buscando PACIENTE por CIPA (" + pacientes.getCipa() + ")");
                pacientes = pacientesService.findByCIPA(pacientes);
            } catch (NoResultException nre) {
                logger.debug("          Almacenando datos del PACIENTE");
                pacientes.setSexos(sexosExt.getSexos());
                pacientes = pacientesService.save(pacientes);
            } finally {
                logger.debug("          Paciente: " + pacientes.toString());
            }

            //EPISODIO
            try {
                episodios.setNhc(nhc);
                episodios.setCentros(centros);
                episodios.setPacientes(pacientes);

                logger.debug("     Buscando EPISODIO por COD_EPISODIO (" + episodios.getCodEpisodio()
                        + "), NHC (" + episodios.getNhc() + "), PROGRAMA (" + episodios.getProgramas()
                        + "), CENTRO (" + episodios.getCentros() + ")");
                episodios = episodiosService.findByCodEpisodioNHCIdProgramaIdCentro(episodios);
            } catch (NoResultException nre) {
                logger.debug("          Almacenando datos del EPISODIO");
                episodios = episodiosService.save(episodios);
            } finally {
                logger.debug("          Episodio: " + episodios.toString());
            }

            //PRESCRIPCIONES
            Prescripciones prescripciones = new Prescripciones();
            try {
                prescripciones.setCodPrescripcion(cod_prescripcion);
                logger.debug("     Buscando PRESCRIPCION por COD_PRESCRIPCION ("
                        + prescripciones.getCodPrescripcion() + ")");
                prescripciones = prescripcionesService.findByCodPrescripcion(prescripciones);
            } catch (NoResultException nre) {
                logger.debug("          Almacenando datos de la PRESCRIPCION: (" + cod_prescripcion + ")");
                Prescripciones prescripcionesOld = new Prescripciones();
                prescripcionesOld
                        .setCodPrescripcion(StringUtils.split(prescripciones.getCodPrescripcion(), "-")[0] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[1] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[2] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[3] + "-"
                                + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[4]);
                List<Prescripciones> prescripcioneses = prescripcionesService
                        .findLikeCodPrescripcion(prescripcionesOld);
                for (Prescripciones prescripcionesUpd : prescripcioneses) {
                    if (StringUtils.equals(StringUtils.split(prescripcionesUpd.getCodPrescripcion(), "-")[7],
                            StringUtils.split(prescripciones.getCodPrescripcion(), "-")[7])) {
                        logger.debug("               Estableciendo fecha de fin en la prescripcion: "
                                + prescripcionesUpd.toString());
                        prescripcionesUpd.setFechaFin(new Date());
                        prescripcionesService.save(prescripcionesUpd);
                    }
                }

                prescripciones.setEpisodios(episodios);
                prescripciones.setMarcas(marcas);
                prescripciones.setMedicos(medicos);
                prescripciones.setDosis(dosis_prescrita);
                prescripciones.setFechaIni(fecha_ini_prescripcion);
                prescripciones.setPautas(pautasExt.getPautas());
                prescripciones.setSecuencias(secuenciasExt.getSecuencias());
                prescripciones.setCodPrescripcion(cod_prescripcion);
                prescripciones.setUnidMed(unidMedExt.getUnidMed());
                prescripciones = prescripcionesService.save(prescripciones);
            } finally {
                logger.debug("          Prescripcion: " + prescripciones.toString());
            }

            //ADMINISTRACIONES
            Administraciones administraciones = new Administraciones();
            try {
                administraciones.setCodAdministracion(cod_administracion);
                logger.debug("     Buscando ADMINISTRACIONES por COD_ADMINISTRACION ("
                        + administraciones.getCodAdministracion() + ")");
                administraciones = findByCodAdministracion(administraciones);
            } catch (NoResultException nre) {
                administraciones.setPrescripciones(prescripciones);
                administraciones.setFormasFar(formasFarExt.getFormasFar());
                administraciones.setCantidad(dosis_administrada);
                administraciones.setFechaAdm(fecha_administracion);
                save(administraciones);
            } finally {
                logger.debug("          Administraciones: " + administraciones.toString());
            }
            logger.info("FINALIZANDO EL ALMACENAMIENTO DEL MOVIMIENTO ENTRANTE");
        }
    } catch (Exception e) {
        throw new Exception("SE HAN PRODUCIDO ERRORES AL PROCESAR EL MOVIMIENTO: \n" + e.getMessage() != null
                ? e.getMessage()
                : e.toString());
    }
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

/**
 * Get mapping detail for some exposed port.
 * @param externalPort external port/*from w w w.  java2 s  . c o  m*/
 * @param portType port type
 * @return port mapping information for that external port
 * @throws NullPointerException if portType is {@code null}
 * @throws IllegalArgumentException if {@code externalPort} isn't between {@code 0} to {@code 65535}, or if the {@code externalPort}
 * isn't between the external port range specified by the service (if one was specified)
 * @throws ResponseException if the router responds with an error
 */
public PortMappingInfo getMappingDetails(int externalPort, PortType portType) {
    // CHECKSTYLE:ON
    Validate.inclusiveBetween(0, 65535, externalPort); // 0 = wildcard, any unassigned port? may not be supported according to docs
    Validate.notNull(portType);

    if (externalPortRange != null) {
        Validate.inclusiveBetween((long) externalPortRange.getMinimum(), (long) externalPortRange.getMaximum(),
                (long) externalPort);
    }

    Map<String, String> respParams = performRequest("GetSpecificPortMappingEntry",
            ImmutablePair.of("NewRemoteHost", ""), ImmutablePair.of("NewExternalPort", "" + externalPort),
            ImmutablePair.of("NewProtocol", portType.name()));

    try {
        int internalPort = NumberUtils.createInteger(respParams.get("NewInternalPort"));
        InetAddress internalClient = InetAddress.getByName(respParams.get("NewInternalClient"));
        long remainingDuration = NumberUtils.createInteger(respParams.get("NewLeaseDuration"));

        return new PortMappingInfo(internalPort, externalPort, portType, internalClient, remainingDuration);
    } catch (UnknownHostException | NumberFormatException | NullPointerException e) {
        throw new ResponseException(e);
    }
}