Example usage for org.apache.commons.lang3.time DateFormatUtils formatUTC

List of usage examples for org.apache.commons.lang3.time DateFormatUtils formatUTC

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateFormatUtils formatUTC.

Prototype

public static String formatUTC(final Date date, final String pattern) 

Source Link

Document

Formats a date/time into a specific pattern using the UTC time zone.

Usage

From source file:com.dominion.salud.mpr.hl7.AbstractParser.java

/**
 * Dado un mensaje HL7 genera un mensaje NACK de respuesta erronea basado en
 * el mensaje original./*  w w  w .  ja  va  2s .  com*/
 * <p>
 * @param message base para generar la respuesta
 * @param text a mostrar en el campo MSA.3
 * <p>
 * @return NACK basado en el mensaje original
 */
public ACK generateNACK(Message message, String text) {
    if (message != null) {
        try {
            ACK ack = (ACK) message.generateACK();

            //MSH
            ack.getMSH().getDateTimeOfMessage().getTime()
                    .setValue(DateFormatUtils.formatUTC(System.currentTimeMillis(), "yyyyMMddHHmmss")); //MSH.7.1
            ack.getMSH().getMessageControlID().setValue(new NanoTimeGenerator().getID()); //MSH.10
            //MSA
            ack.getMSA().getAcknowledgmentCode().setValue("AE");
            //ERR
            ack.getERR().getHL7ErrorCode().getIdentifier().setValue("207");
            ack.getERR().getSeverity().setValue("E");
            ack.getERR().getDiagnosticInformation().setValue(text);

            return ack;
        } catch (HL7Exception | IOException e) {
            return generateNACK(e.toString());
        }
    } else {
        return generateNACK(text);
    }
}

From source file:com.ibm.iotf.devicemgmt.device.DeviceLocation.java

/**
 * Return the <code>JsonObject</code> representation of the <code>DeviceLocation</code> object.
 * @return JsonObject object/*from w ww.j  ava 2 s.  c o m*/
 */
public JsonObject toJsonObject() {
    JsonObject json = new JsonObject();
    json.addProperty(this.latitude.getResourceName(), latitude.getValue());
    json.addProperty(this.longitude.getResourceName(), longitude.getValue());
    if (elevation != null) {
        json.addProperty(this.elevation.getResourceName(), elevation.getValue());
    }

    String utcTime = DateFormatUtils.formatUTC(measuredDateTime.getValue(),
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());

    json.addProperty(this.measuredDateTime.getResourceName(), utcTime);

    if (accuracy != null) {
        json.addProperty(this.accuracy.getResourceName(), accuracy.getValue());
    }
    return json;
}

From source file:com.norconex.commons.lang.time.YearMonthDay.java

public String toString(String pattern) {
    return DateFormatUtils.formatUTC(toDate(), pattern);
}

From source file:com.ibm.iotf.devicemgmt.device.ManagedDevice.java

/**
 * Update the location of the device. This method converts the
 * date in the required format. The caller just need to pass the date in java.util.Date format
 *
 * @param latitude   Latitude in decimal degrees using WGS84
 * @param longitude Longitude in decimal degrees using WGS84
 * @param elevation   Elevation in meters using WGS84
 * @param measuredDateTime When the location information is retrieved
 * @param accuracy   Accuracy of the position in meters
 *
 * @return code indicating whether the update is successful or not
 *        (200 means success, otherwise unsuccessful)
        //ww  w . j a v a 2  s.  co m
 */
public int updateLocation(Double latitude, Double longitude, Double elevation, Date measuredDateTime,
        Double accuracy) {
    final String METHOD = "updateLocation";
    JsonObject jsonData = new JsonObject();

    JsonObject json = new JsonObject();
    json.addProperty("longitude", longitude);
    json.addProperty("latitude", latitude);
    if (elevation != null) {
        json.addProperty("elevation", elevation);
    }
    String utcTime = DateFormatUtils.formatUTC(measuredDateTime,
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    json.addProperty("measuredDateTime", utcTime);

    if (accuracy != null) {
        json.addProperty("accuracy", accuracy);
    }

    jsonData.add("d", json);

    try {
        JsonObject response = sendAndWait(client.getDMAgentTopic().getUpdateLocationTopic(), jsonData,
                REGISTER_TIMEOUT_VALUE);
        if (response != null) {
            return response.get("rc").getAsInt();
        }
    } catch (MqttException e) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, e.toString());
    }

    return 0;
}

From source file:com.ibm.iotf.devicemgmt.device.ManagedDevice.java

/**
 * The Log message that needs to be added to the Watson IoT Platform.
 *
 * @param message The Log message that needs to be added to the Watson IoT Platform.
 * @param timestamp The Log timestamp//from  w w  w  . jav  a 2  s  .c  o m
 * @param severity The Log severity
 * @param data The optional diagnostic string data -
 *             The library will encode the data in base64 format as required by the Platform
 * @return code indicating whether the update is successful or not
 *        (200 means success, otherwise unsuccessful)
 */
public int addLog(String message, Date timestamp, LogSeverity severity, String data) {
    final String METHOD = "addLog";
    JsonObject jsonData = new JsonObject();
    JsonObject log = new JsonObject();
    log.add("message", new JsonPrimitive(message));
    log.add("severity", new JsonPrimitive(severity.getSeverity()));
    String utcTime = DateFormatUtils.formatUTC(timestamp,
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    log.add("timestamp", new JsonPrimitive(utcTime));

    if (data != null) {
        byte[] encodedBytes = Base64.encodeBase64(data.getBytes());
        log.add("data", new JsonPrimitive(new String(encodedBytes)));
    }
    jsonData.add("d", log);

    try {
        JsonObject response = sendAndWait(client.getDMAgentTopic().getAddDiagLogTopic(), jsonData,
                REGISTER_TIMEOUT_VALUE);
        if (response != null) {
            return response.get("rc").getAsInt();
        }
    } catch (MqttException e) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, e.toString());
    }
    return 0;
}

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   w  w w.  j a v  a 2  s  .  co  m*/

    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.ibm.iotf.devicemgmt.gateway.ManagedGateway.java

/**
 * Update the location of the device connected through the Gateway. This method converts the 
 * date in the required format. The caller just need to pass the date in java.util.Date format.
 * /*from w w  w  .j av  a  2  s.  com*/
    * @param typeId The device type of the device connected to the Gateway
 * @param deviceId The deviceId of the device connected to the Gateway
 * @param latitude   Latitude in decimal degrees using WGS84
 * @param longitude Longitude in decimal degrees using WGS84
 * @param elevation   Elevation in meters using WGS84
 * @param measuredDateTime Date of location measurement
 * @param updatedDateTime Date of the update to the device information
 * @param accuracy   Accuracy of the position in meters
 * 
 * @return code indicating whether the update is successful or not 
 *        (200 means success, otherwise unsuccessful)
        
 */
public int updateDeviceLocation(String typeId, String deviceId, Double latitude, Double longitude,
        Double elevation, Date measuredDateTime, Date updatedDateTime, Double accuracy) {

    final String METHOD = "updateLocation";

    String key = typeId + ':' + deviceId;
    ManagedGatewayDevice mc = (ManagedGatewayDevice) this.devicesMap.get(key);
    if (mc == null) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD,
                "The device is not a managed device, so can not send the request");
        return -1;
    }

    JsonObject jsonData = new JsonObject();

    JsonObject json = new JsonObject();
    json.addProperty("longitude", longitude);
    json.addProperty("latitude", latitude);
    if (elevation != null) {
        json.addProperty("elevation", elevation);
    }
    String utcTime = DateFormatUtils.formatUTC(measuredDateTime,
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    json.addProperty("measuredDateTime", utcTime);

    if (updatedDateTime != null) {
        utcTime = DateFormatUtils.formatUTC(updatedDateTime,
                DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
        json.addProperty("updatedDateTime", utcTime);
    }

    if (accuracy != null) {
        json.addProperty("accuracy", accuracy);
    }

    jsonData.add("d", json);

    try {
        JsonObject response = sendAndWait(mc.getDMAgentTopic().getUpdateLocationTopic(), jsonData,
                REGISTER_TIMEOUT_VALUE);
        if (response != null) {
            return response.get("rc").getAsInt();
        }
    } catch (MqttException e) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, e.toString());
    }

    return 0;
}

From source file:com.ibm.iotf.devicemgmt.gateway.ManagedGateway.java

/**
 * Adds a Device(connected via the Gateway) Log message to the IBM Watson IoT Platform.
 * // w w w  .  j  a v  a  2  s  .c  o m
 * This method converts the timestamp in the required format. 
 * The caller just need to pass the timestamp in java.util.Date format.
 * 
 * @param typeId The device type of the device connected to the Gateway.
 * @param deviceId The deviceId of the device connected to the Gateway.
 * @param message The Log message that needs to be added to the IBM Watson IoT Platform.
 * @param timestamp The Log timestamp
 * @param severity The {@link com.ibm.iotf.devicemgmt.LogSeverity}
 * @param data The optional diagnostic string data - 
 *             The library will encode the data in base64 format as required by the Platform .
 * 
 * @return code indicating whether the update is successful or not 
 *        (200 means success, otherwise unsuccessful).
 */
public int addDeviceLog(String typeId, String deviceId, String message, Date timestamp, LogSeverity severity,
        String data) {

    final String METHOD = "addDeviceLog";
    String key = typeId + ':' + deviceId;
    ManagedGatewayDevice mc = (ManagedGatewayDevice) this.devicesMap.get(key);
    if (mc == null) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD,
                "The device is not a managed device, so can not send the request");
        return -1;
    }

    JsonObject jsonData = new JsonObject();
    JsonObject log = new JsonObject();
    log.add("message", new JsonPrimitive(message));
    log.add("severity", new JsonPrimitive(severity.getSeverity()));
    String utcTime = DateFormatUtils.formatUTC(timestamp,
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    log.add("timestamp", new JsonPrimitive(utcTime));

    if (data != null) {
        byte[] encodedBytes = Base64.encodeBase64(data.getBytes());
        log.add("data", new JsonPrimitive(new String(encodedBytes)));
    }
    jsonData.add("d", log);

    try {
        JsonObject response = sendAndWait(mc.getDMAgentTopic().getAddDiagLogTopic(), jsonData,
                REGISTER_TIMEOUT_VALUE);
        if (response != null) {
            return response.get("rc").getAsInt();
        }
    } catch (MqttException e) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, e.toString());
    }
    return 0;
}

From source file:com.ibm.iotf.client.api.APIClient.java

/**
 * Adds an error code to the list of error codes for the device. 
 * The list may be pruned as the new entry is added.
 * //from  www  .  j  a  va2  s.  co  m
 * <p> Refer to  
 * <a href="https://docs.internetofthings.ibmcloud.com/swagger/v0002.html#!/Device_Diagnostics/post_device_types_typeId_devices_deviceId_diag_errorCodes">link</a> 
 * for more information about the schema to be used </p>
 * 
  * @param deviceType String which contains device type
 * @param deviceId String which contains device id
 * @param errorcode ErrorCode to be added in integer format
 * @param date current date (can be null)
 * 
 * @return boolean containing the status of the add operation.
 *  
 * @throws IoTFCReSTException Failure in adding the error codes
 */

public boolean addDiagnosticErrorCode(String deviceType, String deviceId, int errorcode, Date date)
        throws IoTFCReSTException {

    JsonObject ec = new JsonObject();
    ec.addProperty("errorCode", errorcode);
    if (date == null) {
        date = new Date();
    }
    String utcTime = DateFormatUtils.formatUTC(date,
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());

    ec.addProperty("timestamp", utcTime);
    return addDiagnosticErrorCode(deviceType, deviceId, ec);
}