Example usage for org.apache.commons.lang3 StringUtils equalsIgnoreCase

List of usage examples for org.apache.commons.lang3 StringUtils equalsIgnoreCase

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils equalsIgnoreCase.

Prototype

public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) 

Source Link

Document

Compares two CharSequences, returning true if they represent equal sequences of characters, ignoring case.

null s are handled without exceptions.

Usage

From source file:com.github.binlee1990.spider.movie.spider.MovieCrawler.java

private void setFilmReviewCount(Elements countElements, FilmReview filmReview) {
    countElements.forEach(countElement -> {
        String countDesc = StringUtils.trimToEmpty(countElement.select(".fm-mu-label").text());
        String countStr = StringUtils.trimToEmpty(countElement.select(".fm-mu-number").text());
        if (StringUtils.isNotBlank(countDesc) && StringUtils.isNotBlank(countStr)) {
            int count = 0;
            try {
                count = Integer.parseInt(countStr);
            } catch (Exception e) {
            }/*from  w  w  w  .j a va 2  s.  c o m*/
            if (count < 0) {
                count = 0;
            }

            if (StringUtils.equalsIgnoreCase(countDesc, "")) {
                filmReview.setCountPlan(count);
            }
            if (StringUtils.equalsIgnoreCase(countDesc, "")) {
                filmReview.setCountWatched(count);
            }
            if (StringUtils.equalsIgnoreCase(countDesc, "")) {
                filmReview.setCountLike(count);
            }
            if (StringUtils.equalsIgnoreCase(countDesc, "?")) {
                filmReview.setCountDislike(count);
            }
        }
    });
}

From source file:io.wcm.handler.media.format.impl.MediaFormatHandlerImpl.java

/**
 * Detect all matching media formats.//from   ww w . j  a v a 2 s . co  m
 * @param extension File extension
 * @param fileSize File size
 * @param width Image width (or 0 if not image)
 * @param height Image height (or 0 if not image)
 * @return Matching media formats sorted by their ranking or an empty list if no matching format was found
 */
@Override
public SortedSet<MediaFormat> detectMediaFormats(String extension, long fileSize, long width, long height) {

    // sort media formats by ranking
    SortedSet<MediaFormat> matchingFormats = new TreeSet<>(new MediaFormatRankingComparator());

    for (MediaFormat mediaFormat : getMediaFormats()) {

        // skip media formats with negative ranking
        if (mediaFormat.getRanking() < 0) {
            continue;
        }

        // check extension
        boolean extensionMatch = false;
        if (mediaFormat.getExtensions() != null) {
            for (String ext : mediaFormat.getExtensions()) {
                if (StringUtils.equalsIgnoreCase(ext, extension)) {
                    extensionMatch = true;
                    break;
                }
            }
        } else {
            extensionMatch = true;
        }

        // check file size
        boolean fileSizeMatch = false;
        if (mediaFormat.getFileSizeMax() > 0) {
            fileSizeMatch = (fileSize <= mediaFormat.getFileSizeMax());
        } else {
            fileSizeMatch = true;
        }

        // width/height match
        boolean dimensionMatch = false;
        if (width > 0 && height > 0) {
            dimensionMatch = (mediaFormat.getEffectiveMinWidth() == 0
                    || width >= mediaFormat.getEffectiveMinWidth())
                    && (mediaFormat.getEffectiveMaxWidth() == 0 || width <= mediaFormat.getEffectiveMaxWidth())
                    && (mediaFormat.getEffectiveMinHeight() == 0
                            || height >= mediaFormat.getEffectiveMinHeight())
                    && (mediaFormat.getEffectiveMaxHeight() == 0
                            || height <= mediaFormat.getEffectiveMaxHeight());
        } else {
            dimensionMatch = true;
        }

        boolean ratioMatch = false;
        if (mediaFormat.hasRatio() && width > 0 && height > 0) {
            double formatRatio = mediaFormat.getRatio();
            double ratio = (double) width / height;
            ratioMatch = (ratio > formatRatio - RATIO_TOLERANCE) && (ratio < formatRatio + RATIO_TOLERANCE);
        } else {
            ratioMatch = true;
        }

        if (extensionMatch && fileSizeMatch && dimensionMatch && ratioMatch) {
            matchingFormats.add(mediaFormat);
        }
    }

    return matchingFormats;
}

From source file:de.micromata.genome.gwiki.jetty.GWikiInitialSetup.java

protected StandaloneDatabases getDataBase() {
    do {/*from w  w  w.j a  va2s .c  o  m*/
        message("Select a Database type: ");
        for (StandaloneDatabases db : StandaloneDatabases.values()) {
            message(" (" + db.getNum() + ") " + db.getDescription());
        }
        message(" E(x)it");

        String input = getInput("1, 2, 3 or x: ");
        if (StringUtils.isBlank(input) == true) {
            continue;
        }
        if (StringUtils.equalsIgnoreCase(input, "x") == true) {
            return null;
        }
        StandaloneDatabases db = StandaloneDatabases.getDatabaseByInput(input);
        if (db != null) {
            return db;
        }
    } while (true);
}

From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java

/**
 * Refresh the UI with data from the product
 *//*from   w  w  w. j a  va 2s .c  o  m*/
public void updateUI() {

    // Title
    this.setTitle(mProduct.getName());

    // Images
    if (mProduct.getGalleryImageURLs() != null) {
        GalleryAdapter adapter = new GalleryAdapter(this, mProduct.getGalleryImageURLs());
        Gallery gallery = (Gallery) findViewById(R.id.galleryImages);
        gallery.setAdapter(adapter);

        // Set the onClick listener for the gallery
        gallery.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
                viewImage(position);

            }
        });
    }

    // Reviews
    TextView reviewTextView = (TextView) findViewById(R.id.textViewReviews);
    reviewTextView.setText(this.getResources().getString(R.string.show_reviews, mProduct.getReviews().size()));

    // Rating (stars)
    RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBarRating);
    if (mProduct.getAverageRating() != null) {
        ratingBar.setRating(mProduct.getAverageRating().floatValue());
    }

    // Promotions
    TextView promotionsTextView = (TextView) findViewById(R.id.textViewPromotion);
    if (mProduct.getPotentialPromotions().size() == 0) {
        promotionsTextView.setVisibility(View.GONE);
    } else {
        if (mProduct.getPotentialPromotions() != null && !mProduct.getPotentialPromotions().isEmpty()) {
            promotionsTextView.setText(
                    Html.fromHtml(Product.generatePromotionString(mProduct.getPotentialPromotions().get(0))));
            StringUtil.removeUnderlines((Spannable) promotionsTextView.getText());
        }

    }

    TextView priceTextView = (TextView) findViewById(R.id.textViewPrice);
    priceTextView.setText(mProduct.getPrice().getFormattedValue());

    // Description
    TextView descriptionTextView = (TextView) findViewById(R.id.textViewDescription);
    descriptionTextView.setText(mProduct.getDescription());

    // Stock level
    TextView stockLevelTextView = (TextView) findViewById(R.id.textViewStockLevel);
    String stockLevelText = mProduct.getStockLevelText(Hybris.getAppContext());
    if (mProduct.getStock().getStockLevel() > 0) {
        stockLevelText = mProduct.getStock().getStockLevel() + " "
                + mProduct.getStockLevelText(Hybris.getAppContext()).toLowerCase();
    }
    stockLevelTextView.setText(stockLevelText);

    // Disable / Enable the add to cart button
    Button addToCartButton = (Button) findViewById(R.id.buttonAddToCart);

    Button quantityButton = (Button) findViewById(R.id.quantityButton);
    quantityButton.setText(getString(R.string.quantity_button, quantityToAddToCart));

    try {

        if (mProduct.getStock().getStockLevelStatus() != null
                && StringUtils.equalsIgnoreCase(mProduct.getStock().getStockLevelStatus().getCode(),
                        ProductStockLevelStatus.CODE_OUT_OF_STOCK)) {
            addToCartButton.setEnabled(false);
            quantityButton.setEnabled(false);
            quantityButton.setText(R.string.quantity);
        } else {
            addToCartButton.setEnabled(true);
            quantityButton.setEnabled(true);
        }
    } catch (Exception e) {
    }

    invalidateOptionsMenu();
}

From source file:com.ottogroup.bi.asap.pipeline.MicroPipeline.java

/**
 * Subscribes the {@link Component} referenced by the <i>subscriberId</i> to the {@link Component} referenced by the <i>publisherId</i>
 * @param subscriberId//from w ww  .j a v a 2 s  . co m
 * @param publisherId
 * @throws RequiredInputMissingException
 * @throws UnknownComponentException
 * @throws IllegalComponentSubscriptionException thrown in case a component tries to subscribe itself to an {@link Emitter} or a {@link Source} tries to subscribe itself somewhere else
 */
public void subscribe(final String subscriberId, final String publisherId)
        throws RequiredInputMissingException, UnknownComponentException, IllegalComponentSubscriptionException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(subscriberId))
        throw new RequiredInputMissingException("Missing required input for 'subscriberId'");
    if (StringUtils.isBlank(publisherId))
        throw new RequiredInputMissingException("Missing required input for 'publisherId'");
    if (StringUtils.equalsIgnoreCase(subscriberId, publisherId))
        throw new IllegalComponentSubscriptionException("Self-subscriptions are not permitted [subscriberId='"
                + subscriberId + "', publisherId='" + publisherId + "']");
    //
    ///////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////
    // ensure that the subscriber id does not reference a source component,
    // ensure that the publisher id does not reference an emitter component and
    // ensure that subscriber id and publisher id are different
    String sid = StringUtils.lowerCase(StringUtils.trim(subscriberId));
    String pid = StringUtils.lowerCase(StringUtils.trim(publisherId));

    if (this.sourceExecutors.containsKey(sid))
        throw new IllegalComponentSubscriptionException("Source component '" + subscriberId
                + "' is not allowed to subscribe itself to another component");
    if (this.emitterExecutors.containsKey(pid))
        throw new IllegalComponentSubscriptionException("Emitter component '" + publisherId
                + "' is not allowed to serve as publisher for another component");

    // execute subscription
    Mailbox subscriberMailbox = null;
    if (this.operatorExecutors.containsKey(sid)) {
        OperatorExecutor subscriber = this.operatorExecutors.get(sid);
        if (subscriber == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by subscriberId '" + subscriberId + "'");
        subscriberMailbox = subscriber.getMailbox();
    } else if (this.emitterExecutors.containsKey(sid)) {
        EmitterExecutor subscriber = this.emitterExecutors.get(sid);
        if (subscriber == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by subscriberId '" + subscriberId + "'");
        subscriberMailbox = subscriber.getMailbox();
    } else {
        throw new UnknownComponentException(
                "Unknown component referenced by subscriberId '" + subscriberId + "'");
    }

    if (this.operatorExecutors.containsKey(pid)) {
        OperatorExecutor publisher = this.operatorExecutors.get(pid);
        if (publisher == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by publisherId '" + publisherId + "'");
        publisher.subscribe(sid, subscriberMailbox);
    } else if (this.sourceExecutors.containsKey(pid)) {
        SourceExecutor publisher = this.sourceExecutors.get(pid);
        if (publisher == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by publisherId '" + publisherId + "'");
        publisher.subscribe(sid, subscriberMailbox);
    } else {
        throw new UnknownComponentException(
                "Unknown component referenced by publisherId '" + publisherId + "'");
    }
    //
    ///////////////////////////////////////////////////////////////////

}

From source file:com.nridge.core.base.field.data.DataBag.java

/**
 * Returns the offset of the field in the bag collection that
 * matches the field name parameter (case insensitive).
 *
 * @param aName Field name./*from w  w w  .  j av  a  2 s  .c o m*/
 *
 * @return Offset value or -1 if not found.
 */
public int getOffsetByNameIgnoreCase(String aName) {
    int offset = 0;
    for (DataField dataField : mFields) {
        if (StringUtils.equalsIgnoreCase(dataField.getName(), aName))
            return offset;
        else
            offset++;
    }

    return -1;
}

From source file:com.glaf.dts.transform.MxTransformThread.java

@SuppressWarnings("unchecked")
public void run() {
    logger.debug(taskId + "----------------execution-----------------");
    TransformTask task = transformTaskService.getTransformTask(taskId);
    if (task != null) {
        if (task.getStatus() == 9 || task.getRetryTimes() > 3) {
            return;
        }/* ww w . j a  v a2  s. c om*/
        task.setStartTime(new java.util.Date());
        task.setRetryTimes(task.getRetryTimes() + 1);
        task.setStatus(1);
        transformTaskService.save(task);
    }

    List<TableModel> resultList = new java.util.ArrayList<TableModel>();
    Map<String, Object> singleDataMap = new HashMap<String, Object>();
    Connection conn = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    boolean success = true;
    long start = System.currentTimeMillis();
    logger.debug("start:" + DateUtils.getDateTime(new java.util.Date()));
    try {
        Database database = getDatabaseService().getDatabaseById(queryDefinition.getDatabaseId());
        if (database != null) {
            conn = DBConnectionFactory.getConnection(database.getName());
        } else {
            conn = DBConnectionFactory.getConnection();
        }

        logger.debug("conn:" + conn.toString());

        String sql = queryDefinition.getSql();
        sql = QueryUtils.replaceSQLVars(sql);
        List<Object> values = null;
        if (paramMap != null) {
            SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, paramMap);
            sql = sqlExecutor.getSql();
            values = (List<Object>) sqlExecutor.getParameter();
        }

        logger.debug("--------------execute query----------------------");
        logger.debug(queryDefinition.getTitle());

        logger.debug("::sql::" + sql);
        psmt = conn.prepareStatement(sql);

        if (values != null && !values.isEmpty()) {
            JdbcUtils.fillStatement(psmt, values);
            logger.debug("::values::" + values);
        }

        List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>();

        rs = psmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            int sqlType = rsmd.getColumnType(i);
            ColumnDefinition column = new ColumnDefinition();
            column.setColumnName(rsmd.getColumnName(i));
            column.setColumnLabel(rsmd.getColumnLabel(i));
            column.setJavaType(FieldType.getJavaType(sqlType));
            column.setPrecision(rsmd.getPrecision(i));
            column.setScale(rsmd.getScale(i));
            columns.add(column);
        }

        Set<String> cols = new HashSet<String>();

        while (rs.next()) {
            int index = 0;
            TableModel rowModel = new TableModel();

            ColumnModel cell01 = new ColumnModel();
            cell01.setColumnName("ID");
            cell01.setType("String");
            rowModel.addColumn(cell01);
            rowModel.setIdColumn(cell01);
            cols.add(cell01.getColumnName());

            ColumnModel cell04 = new ColumnModel();
            cell04.setColumnName("AGGREGATIONKEY");
            cell04.setType("String");
            rowModel.addColumn(cell04);
            cols.add(cell04.getColumnName());

            Iterator<ColumnDefinition> iterator = columns.iterator();
            while (iterator.hasNext()) {
                ColumnDefinition column = iterator.next();
                /**
                 * ????
                 */
                if (cols.contains(column.getColumnName())) {
                    continue;
                }
                ColumnModel cell = new ColumnModel();
                String columnName = column.getColumnName();
                String javaType = column.getJavaType();
                cell.setColumnName(columnName);
                cell.setType(javaType);
                index = index + 1;
                if ("String".equals(javaType)) {
                    String value = rs.getString(columnName);
                    cell.setStringValue(value);
                    cell.setValue(value);
                } else if ("Integer".equals(javaType)) {
                    try {
                        Integer value = rs.getInt(columnName);
                        cell.setIntValue(value);
                        cell.setValue(value);
                    } catch (Exception e) {
                        String str = rs.getString(columnName);
                        logger.error("integer:" + str);
                        str = StringTools.replace(str, "$", "");
                        str = StringTools.replace(str, "", "");
                        str = StringTools.replace(str, ",", "");
                        NumberFormat fmt = NumberFormat.getInstance();
                        Number num = fmt.parse(str);
                        cell.setIntValue(num.intValue());
                        cell.setValue(cell.getIntValue());
                        logger.debug("?:" + num.intValue());
                    }
                } else if ("Long".equals(javaType)) {
                    try {
                        Long value = rs.getLong(columnName);
                        cell.setLongValue(value);
                        cell.setValue(value);
                    } catch (Exception e) {
                        String str = rs.getString(columnName);
                        logger.error("long:" + str);
                        str = StringTools.replace(str, "", "");
                        str = StringTools.replace(str, ",", "");
                        NumberFormat fmt = NumberFormat.getInstance();
                        Number num = fmt.parse(str);
                        cell.setLongValue(num.longValue());
                        cell.setValue(cell.getLongValue());
                        logger.debug("?:" + num.longValue());
                    }
                } else if ("Double".equals(javaType)) {
                    try {
                        Double d = rs.getDouble(columnName);
                        cell.setDoubleValue(d);
                        cell.setValue(d);
                    } catch (Exception e) {
                        String str = rs.getString(columnName);
                        logger.error("double:" + str);
                        str = StringTools.replace(str, "", "");
                        str = StringTools.replace(str, ",", "");
                        NumberFormat fmt = NumberFormat.getInstance();
                        Number num = fmt.parse(str);
                        cell.setDoubleValue(num.doubleValue());
                        cell.setValue(cell.getDoubleValue());
                        logger.debug("?:" + num.doubleValue());
                    }
                } else if ("Boolean".equals(javaType)) {
                    Boolean value = rs.getBoolean(columnName);
                    cell.setBooleanValue(value);
                    cell.setValue(value);
                } else if ("Date".equals(javaType)) {
                    Date value = rs.getTimestamp(columnName);
                    cell.setDateValue(value);
                    cell.setValue(value);
                } else {
                    String value = rs.getString(columnName);
                    cell.setStringValue(value);
                    cell.setValue(value);
                }
                rowModel.addColumn(cell);
                if (resultList.isEmpty()) {
                    singleDataMap.put(column.getColumnLabel(), cell.getValue());
                }
            }
            resultList.add(rowModel);
        }

        logger.debug("--------------------resultList size:" + resultList.size());

    } catch (Exception ex) {
        success = false;
        ex.printStackTrace();
        logger.error(ex);
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
        if (!success) {
            if (task != null) {
                task.setStatus(2);
                transformTaskService.save(task);
            }
        }
    }

    logger.debug("--------------execute mybatis save----------------------");

    try {

        if (!StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")) {
            TransformTable tbl = new TransformTable();
            tbl.createOrAlterTable(tableDefinition);
        }

        List<ColumnDefinition> columns = DBUtils.getColumnDefinitions(tableDefinition.getTableName());
        if (columns != null && !columns.isEmpty()) {
            tableDefinition.setColumns(columns);
        }

        if (resultList != null && !resultList.isEmpty() && tableDefinition.getTableName() != null
                && tableDefinition.getAggregationKeys() != null) {
            logger.debug("RotatingFlag:" + queryDefinition.getRotatingFlag());
            logger.debug("RotatingColumn:" + queryDefinition.getRotatingColumn());
            /**
             * ????
             */
            if (StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")
                    && StringUtils.isNotEmpty(queryDefinition.getRotatingColumn()) && resultList.size() == 1) {

                logger.debug("?dataMap?:" + singleDataMap);
                logger.debug("AggregationKeys:" + tableDefinition.getAggregationKeys());
                ColumnDefinition idField = columnMap.get(tableDefinition.getAggregationKeys().toLowerCase());
                ColumnDefinition field = columnMap.get(queryDefinition.getRotatingColumn().toLowerCase());
                logger.debug("idField:" + idField);
                logger.debug("field:" + field);
                if (idField != null && field != null) {
                    String javaType = field.getJavaType();
                    List<TableModel> list = new ArrayList<TableModel>();
                    Set<Entry<String, Object>> entrySet = singleDataMap.entrySet();
                    for (Entry<String, Object> entry : entrySet) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (key == null || value == null) {
                            continue;
                        }
                        TableModel tableModel = new TableModel();
                        tableModel.setTableName(queryDefinition.getTargetTableName());
                        ColumnModel cell = new ColumnModel();
                        cell.setColumnName(queryDefinition.getRotatingColumn());
                        cell.setType(javaType);

                        // logger.debug(cell.getColumnName()+"->"+javaType);

                        if ("String".equals(javaType)) {
                            cell.setStringValue(ParamUtils.getString(singleDataMap, key));
                            cell.setValue(cell.getStringValue());
                        } else if ("Integer".equals(javaType)) {
                            cell.setIntValue(ParamUtils.getInt(singleDataMap, key));
                            cell.setValue(cell.getIntValue());
                        } else if ("Long".equals(javaType)) {
                            cell.setLongValue(ParamUtils.getLong(singleDataMap, key));
                            cell.setValue(cell.getLongValue());
                        } else if ("Double".equals(javaType)) {
                            cell.setDoubleValue(ParamUtils.getDouble(singleDataMap, key));
                            cell.setValue(cell.getDoubleValue());
                        } else if ("Date".equals(javaType)) {
                            cell.setDateValue(ParamUtils.getDate(singleDataMap, key));
                            cell.setValue(cell.getDateValue());
                        } else {
                            cell.setValue(value);
                        }

                        tableModel.addColumn(cell);

                        ColumnModel idColumn = new ColumnModel();
                        idColumn.setColumnName(tableDefinition.getAggregationKeys());
                        idColumn.setJavaType(idField.getJavaType());
                        idColumn.setValue(key);
                        tableModel.setIdColumn(idColumn);
                        list.add(tableModel);
                    }
                    logger.debug("update datalist:" + list);
                    tableDataService.updateTableData(list);
                }
            } else {
                tableDataService.saveAll(tableDefinition, null, resultList);
            }
        }

        resultList.clear();
        resultList = null;

        long time = System.currentTimeMillis() - start;

        if (task != null) {
            task.setEndTime(new java.util.Date());
            task.setStatus(9);
            task.setDuration(time);
        }
        logger.debug("execute time(ms)--------------------------" + time);
    } catch (Exception ex) {
        if (task != null) {
            task.setStatus(2);
        }
        ex.printStackTrace();
        logger.error(ex);
        throw new RuntimeException(ex);
    } finally {
        if (task != null) {
            transformTaskService.save(task);
            if (task.getStatus() != 9) {
                this.run();
            }
        }
    }
}

From source file:com.bekwam.resignator.model.ConfigurationDataSourceImpl.java

@Override
public String suggestUniqueProfileName(String profileName) {

    int counter = 2;

    do {//www .j  a  v  a2 s. co  m
        final String pn = profileName + "-" + counter;

        boolean found = configuration.get().getProfiles().stream()
                .anyMatch(p -> StringUtils.equalsIgnoreCase(p.getProfileName(), pn));

        if (!found) {
            return pn;
        }

        counter++;
    } while (true);
}

From source file:it.cnr.isti.hpc.wikipedia.parser.ArticleParser.java

private void setDisambiguation(Article a) {

    for (String disambiguation : locale.getDisambigutionIdentifiers()) {
        if (StringUtils.containsIgnoreCase(a.getTitle(), disambiguation)) {
            a.setType(Type.DISAMBIGUATION);
            return;
        }/*from ww w  . ja v  a  2s  . co m*/
        for (Template t : a.getTemplates()) {
            if (StringUtils.equalsIgnoreCase(t.getName(), disambiguation)) {
                a.setType(Type.DISAMBIGUATION);
                return;

            }
        }

    }
}

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

/**
 *
 * @param message//from   www.java 2  s. co  m
 * @throws Exception
 */
@Override
@Transactional(noRollbackFor = { NoResultException.class }, rollbackFor = { Exception.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<>();
    int contador = 0;

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

        List<ZDS_O13_ORDER> zds_o13_orders = hl7message.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 = (Z01) zds_o13_order.getZ01();
            OBX obx = zds_o13_order.getOBSERVATION().getOBX();

            //Z01.15 - Datos del Acuerdo
            logger.debug("     Procesando datos del ACUERDO (" + z01.getAcuerdo().getIdentifier().getValue()
                    + ") " + z01.getAcuerdo().getText().getValue());
            Acuerdos acuerdos = null;
            if (StringUtils.isNotBlank(z01.getAcuerdo().getIdentifier().getValue())) {
                try {
                    acuerdos = new Acuerdos();
                    acuerdos.setCodAcuerdo(z01.getAcuerdo().getIdentifier().getValue());
                    acuerdos = acuerdosService.findByCodAcuerdo(acuerdos);
                    logger.debug("          Z01.15 - Datos del Acuerdo: "
                            + (acuerdos != null ? acuerdos.toString() : "null"));
                } catch (NoResultException nre) {
                    acuerdos = null;
                    logger.debug("          El movimiento no coincide con ningun ACUERDO");
                }
            } else {
                logger.debug("          El movimiento no coincide con ningun ACUERDO");
            }

            //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
            logger.debug("          PID.5 - Paciente: " + pacientes.toString());

            //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
            String cod_episodio = "";
            logger.debug("     Procesando datos del CODIGO DE EPISODIO ("
                    + pv1.getVisitNumber().getIDNumber().getValue() + ")"); //PV1.19.1
            if (StringUtils.isNotBlank(pv1.getVisitNumber().getIDNumber().getValue())) {
                cod_episodio = pv1.getVisitNumber().getIDNumber().getValue();
                logger.debug("          PV1.19.1 - Codigo de Episodio: " + cod_episodio);
            } 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 Dispensacion
            String cod_dispensacion = null;
            logger.debug("     Procesando CODIGO DE DISPENSACION ("
                    + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")"); //ORC.2.1
            if (StringUtils.isNotBlank(orc.getFillerOrderNumber().getEntityIdentifier().getValue())) {
                cod_dispensacion = orc.getFillerOrderNumber().getEntityIdentifier().getValue();
                logger.debug("          ORC.3.1 - Codigo de Dispensacion: " + cod_dispensacion);
            } else {
                logger.error(
                        "          No se puede procesar el movimiento sin INFORMACION en el CAMPO ORC.3.1 - CODIGO DE DISPENSACION ("
                                + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")");
                resultado.add(
                        "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE DISPENSACION");
            }

            //CRITERIOS DE INCLUSION
            //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 (acuerdos != null) {
                    if (acuerdos.getSexos() != null) { //Es un criterio de inclusion del acuerdo
                        if (StringUtils.isNotBlank(pid.getAdministrativeSex().getValue())) {
                            logger.error(
                                    "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo PID.8 - SEXO ("
                                            + pid.getAdministrativeSex().getValue() + ")");
                            resultado.add(
                                    "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: SEXO ("
                                            + pid.getAdministrativeSex().getValue() + ")");
                        } else {
                            logger.error(
                                    "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo PID.8 - SEXO");
                            resultado.add(
                                    "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: SEXO");
                        }
                    } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(pid.getAdministrativeSex().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo PID.8 - SEXO ("
                                            + pid.getAdministrativeSex().getValue() + ")");
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: SEXO ("
                                            + pid.getAdministrativeSex().getValue() + ")");
                        }
                    }
                }
            }

            //Z01.6 - Indicacion
            logger.debug(
                    "     Procesando datos de la INDICACION (" + z01.getIndicacion().getIdentifier().getValue()
                            + ") " + z01.getIndicacion().getText().getValue());
            IndicacionesExt indicacionesExt = new IndicacionesExt();
            try {
                indicacionesExt.setCentros(centros);
                indicacionesExt.setCodIndicacionExt(z01.getIndicacion().getIdentifier().getValue()); //Z01.6.1
                indicacionesExt.setTxtIndicacionExt(z01.getIndicacion().getText().getValue()); //Z01.6.2
                indicacionesExt = indicacionesExtService.traducirEquivalenciaAndInsert(indicacionesExt);
                logger.debug("          Z01.6 - Indicacion: " + indicacionesExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (acuerdos.getAcuIndicacioneses() != null && !acuerdos.getAcuIndicacioneses().isEmpty()) { //Es un criterio de inclusion del acuerdo
                        if (StringUtils.isNotBlank(z01.getIndicacion().getIdentifier().getValue())) {
                            logger.error(
                                    "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.6 - INDICACION ("
                                            + z01.getIndicacion().getIdentifier().getValue() + ") "
                                            + z01.getIndicacion().getText().getValue());
                            resultado.add(
                                    "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: INDICACION ("
                                            + z01.getIndicacion().getIdentifier().getValue() + ") "
                                            + z01.getIndicacion().getText().getValue());
                        } else {
                            logger.error(
                                    "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo Z01.6 - INDICACION");
                            resultado.add(
                                    "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: INDICACION");
                        }
                    } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getIndicacion().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.6 - INDICACION ("
                                            + z01.getIndicacion().getIdentifier().getValue() + ") "
                                            + z01.getIndicacion().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: INDICACION ("
                                            + z01.getIndicacion().getIdentifier().getValue() + ") "
                                            + z01.getIndicacion().getText().getValue());
                        }
                    }
                }
            }

            //Z01.5 - Linea de Tratamiento
            logger.debug("     Procesando datos de la LINEA DE TRATAMIENTO ("
                    + z01.getLineaTrat().getIdentifier().getValue() + ") "
                    + z01.getLineaTrat().getText().getValue());
            LineasTratExt lineasTratExt = new LineasTratExt();
            try {
                lineasTratExt.setCentros(centros);
                lineasTratExt.setCodLineaTratExt(z01.getLineaTrat().getIdentifier().getValue()); //Z01.5.1
                lineasTratExt.setTxtLineaTratExt(z01.getLineaTrat().getText().getValue()); //Z01.5.2
                lineasTratExt = lineasTratExtService.traducirEquivalenciaAndInsert(lineasTratExt);
                logger.debug("          Z01.5 - Linea de Tratamiento: " + lineasTratExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (acuerdos.getAcuLineasTrats() != null && !acuerdos.getAcuLineasTrats().isEmpty()) { //Es un criterio de inclusion del acuerdo
                        if (StringUtils.isNotBlank(z01.getLineaTrat().getIdentifier().getValue())) {
                            logger.error(
                                    "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.5 - LINEA DE TRATAMIENTO ("
                                            + z01.getLineaTrat().getIdentifier().getValue() + ") "
                                            + z01.getLineaTrat().getText().getValue());
                            resultado.add(
                                    "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: LINEA DE TRATAMIENTO ("
                                            + z01.getLineaTrat().getIdentifier().getValue() + ") "
                                            + z01.getLineaTrat().getText().getValue());
                        } else {
                            logger.error(
                                    "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo Z01.5 - LINEA DE TRATAMIENTO");
                            resultado.add(
                                    "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: LINEA DE TRATAMIENTO");
                        }
                    } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getLineaTrat().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.5 - LINEA DE TRATAMIENTO ("
                                            + z01.getLineaTrat().getIdentifier().getValue() + ") "
                                            + z01.getLineaTrat().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: LINEA DE TRATAMIENTO ("
                                            + z01.getLineaTrat().getIdentifier().getValue() + ") "
                                            + z01.getLineaTrat().getText().getValue());
                        }
                    }
                }
            }

            //Z01.2[] - Situaciones Clinicas de Partida
            logger.debug(
                    "     Procesando SITUACIONES CLINICAS DE PARTIDA y VALORES DE SITUACION CLINICA DE PARTIDA");
            List<EpiSitClinica> epiSitClinicas = new ArrayList<>();
            if (z01.getSituacionClinica() != null && z01.getSituacionClinica().length > 0) {
                for (int i = 0; i < z01.getSituacionClinica().length; i++) {
                    logger.debug("          Procesando SITUACION CLINICA DE PARTIDA ("
                            + z01.getSituacionClinica(i).getIdentifier().getValue() + ") "
                            + z01.getSituacionClinica(i).getText().getValue());

                    try {
                        SitClinicaExt sitClinicaExt = new SitClinicaExt();
                        sitClinicaExt.setCentros(centros);
                        sitClinicaExt
                                .setCodSitClinicaExt(z01.getSituacionClinica(i).getIdentifier().getValue()); //Z01.2.1
                        sitClinicaExt.setTxtSitClinicaExt(z01.getSituacionClinica(i).getText().getValue()); //Z01.2.2
                        sitClinicaExt = sitClinicaExtService.traducirEquivalenciaAndInsert(sitClinicaExt);
                        logger.debug(
                                "               Z01.2.(1,2) - Situacion Clinica: " + sitClinicaExt.toString());

                        EpiSitClinica epiSitClinica = new EpiSitClinica();
                        epiSitClinica.setEpisodios(episodios);
                        epiSitClinica.setSitClinica(sitClinicaExt.getSitClinica());
                        epiSitClinicas.add(epiSitClinica);

                        //Z01.2.(4,5) - Valores de Situacion Clinica de Partida
                        List<EpiValSitClinica> epiValSitClinicas = new ArrayList<>();
                        logger.debug("               Procesando VALOR DE SITUACION CLINICA DE PARTIDA ("
                                + z01.getSituacionClinica(i).getAlternateIdentifier().getValue() + ") "
                                + z01.getSituacionClinica(i).getAlternateText().getValue() + " ["
                                + z01.getSituacionClinica(i).getNameOfAlternateCodingSystem() + "]");
                        if (StringUtils
                                .isNotBlank(z01.getSituacionClinica(i).getAlternateIdentifier().getValue())) {
                            try {
                                logger.debug("               Procesando VALOR DE SITUACION CLINICA DE PARTIDA ("
                                        + z01.getSituacionClinica(i).getAlternateIdentifier().getValue() + ") "
                                        + z01.getSituacionClinica(i).getAlternateText().getValue());
                                ValSitClinicaExt valSitClinicaExt = new ValSitClinicaExt();
                                valSitClinicaExt.setCentros(centros);
                                valSitClinicaExt.setCodValSitClinicaExt(
                                        z01.getSituacionClinica(i).getAlternateIdentifier().getValue()); //Z01.2.4
                                valSitClinicaExt.setTxtValSitClinicaExt(
                                        z01.getSituacionClinica(i).getAlternateText().getValue()); //Z01.2.5
                                valSitClinicaExt = valSitClinicaExtService
                                        .traducirEquivalenciaAndInsert(valSitClinicaExt);
                                logger.debug(
                                        "                    Z01.2.(4,5) - Valor de Situacion Clinica de Partida: "
                                                + valSitClinicaExt.toString());

                                EpiValSitClinica epiValSitClinica = new EpiValSitClinica();
                                epiValSitClinica.setEpiSitClinica(epiSitClinica);
                                epiValSitClinica.setValSitClinica(valSitClinicaExt.getValSitClinica());
                                epiValSitClinicas.add(epiValSitClinica);
                            } catch (NoExisteEquivalenciaException neee) {
                                if (acuerdos != null) {
                                    if (acuerdos.getAcuSitClinicas() != null
                                            && !acuerdos.getAcuSitClinicas().isEmpty()) { //Es un criterio de inclusion del acuerdo
                                        if (StringUtils.isNotBlank(z01.getSituacionClinica(i)
                                                .getAlternateIdentifier().getValue())) {
                                            logger.error(
                                                    "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.2.(4,5) - VALOR DE SITUACION CLINICA DE PARTIDA ("
                                                            + z01.getSituacionClinica(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getSituacionClinica(i)
                                                                    .getAlternateText().getValue());
                                            resultado.add(
                                                    "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: VALOR DE SITUACION CLINICA DE PARTIDA ("
                                                            + z01.getSituacionClinica(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getSituacionClinica(i)
                                                                    .getAlternateText().getValue());
                                        } else {
                                            logger.error(
                                                    "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo Z01.2.(4,5) - VALOR DE SITUACION CLINICA DE PARTIDA");
                                            resultado.add(
                                                    "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: VALOR DE SITUACION CLINICA DE PARTIDA");
                                        }
                                    } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                                        if (StringUtils.isNotBlank(z01.getSituacionClinica(i)
                                                .getAlternateIdentifier().getValue())) {
                                            logger.error(
                                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.2.(4,5) - VALOR DE SITUACION CLINICA DE PARTIDA ("
                                                            + z01.getSituacionClinica(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getSituacionClinica(i)
                                                                    .getAlternateText().getValue());
                                            resultado.add(
                                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: VALOR DE SITUACION CLINICA DE PARTIDA ("
                                                            + z01.getSituacionClinica(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getSituacionClinica(i)
                                                                    .getAlternateText().getValue());
                                        }
                                    }
                                }
                            }
                        } else if (StringUtils.isNotBlank(
                                z01.getSituacionClinica(i).getNameOfAlternateCodingSystem().getValue())) {
                            logger.debug("               Procesando VALOR DE SITUACION CLINICA DE PARTIDA ("
                                    + z01.getSituacionClinica(i).getNameOfAlternateCodingSystem().getValue()
                                    + ")");
                            EpiValSitClinica epiValSitClinica = new EpiValSitClinica();
                            epiValSitClinica.setEpiSitClinica(epiSitClinica);
                            epiValSitClinica.setValor(
                                    z01.getSituacionClinica(i).getNameOfAlternateCodingSystem().getValue());
                            epiValSitClinicas.add(epiValSitClinica);
                        }
                        epiSitClinica.setEpiValSitClinicas(epiValSitClinicas);

                    } catch (NoExisteEquivalenciaException neee) {
                        if (acuerdos != null) {
                            if (acuerdos.getAcuSitClinicas() != null
                                    && !acuerdos.getAcuSitClinicas().isEmpty()) { //Es un criterio de inclusion del acuerdo
                                if (StringUtils
                                        .isNotBlank(z01.getSituacionClinica(i).getIdentifier().getValue())) {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.2.(1,2) - SITUACION CLINICA DE PARTIDA ("
                                                    + z01.getSituacionClinica(i).getIdentifier().getValue()
                                                    + ") " + z01.getSituacionClinica(i).getText().getValue());
                                    resultado.add(
                                            "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: SITUACION CLINICA DE PARTIDA ("
                                                    + z01.getSituacionClinica(i).getIdentifier().getValue()
                                                    + ") " + z01.getSituacionClinica(i).getText().getValue());
                                } else {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo Z01.2.(1,2) - SITUACION CLINICA DE PARTIDA");
                                    resultado.add(
                                            "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: SITUACION CLINICA DE PARTIDA");
                                }
                            } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                                if (StringUtils
                                        .isNotBlank(z01.getSituacionClinica(i).getIdentifier().getValue())) {
                                    logger.error(
                                            "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.2.(1,2) - SITUACION CLINICA DE PARTIDA ("
                                                    + z01.getSituacionClinica(i).getIdentifier().getValue()
                                                    + ") " + z01.getSituacionClinica(i).getText().getValue());
                                    resultado.add(
                                            "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: SITUACION CLINICA DE PARTIDA ("
                                                    + z01.getSituacionClinica(i).getIdentifier().getValue()
                                                    + ") " + z01.getSituacionClinica(i).getText().getValue());
                                }
                            }
                        }
                    }
                }
            }

            //Z01.3[] - Marcadores Biologicos
            logger.debug("     Procesando MARCADORES BIOLOGICOS y VALORES DE MARCADOR BIOLOGICO");
            List<EpiMarcaBio> epiMarcaBios = new ArrayList<>();
            if (z01.getMarcadorBiologico() != null && z01.getMarcadorBiologico().length > 0) {
                for (int i = 0; i < z01.getMarcadorBiologico().length; i++) {
                    logger.debug("          Procesando MARCADOR BIOLOGICO ("
                            + z01.getMarcadorBiologico(i).getIdentifier().getValue() + ") "
                            + z01.getMarcadorBiologico(i).getText().getValue());

                    try {
                        MarcaBioExt marcaBioExt = new MarcaBioExt();
                        marcaBioExt.setCentros(centros);
                        marcaBioExt.setCodMarcaBioExt(z01.getMarcadorBiologico(i).getIdentifier().getValue()); //Z01.2.1
                        marcaBioExt.setTxtMarcaBioExt(z01.getMarcadorBiologico(i).getText().getValue()); //Z01.2.2
                        marcaBioExt = marcaBioExtService.traducirEquivalenciaAndInsert(marcaBioExt);
                        logger.debug(
                                "               Z01.3.(1,2) - Marcador Biologico: " + marcaBioExt.toString());

                        EpiMarcaBio epiMarcaBio = new EpiMarcaBio();
                        epiMarcaBio.setEpisodios(episodios);
                        epiMarcaBio.setMarcaBio(marcaBioExt.getMarcaBio());
                        epiMarcaBios.add(epiMarcaBio);

                        //Z01.3.(4,5) - Valores de Marcador Biologico
                        List<EpiValMarcaBio> epiValMarcaBios = new ArrayList<>();
                        logger.debug("               Procesando VALOR DE MARCADOR BIOLOGICO ("
                                + z01.getMarcadorBiologico(i).getAlternateIdentifier().getValue() + ") "
                                + z01.getMarcadorBiologico(i).getAlternateText().getValue() + " ["
                                + z01.getMarcadorBiologico(i).getNameOfAlternateCodingSystem().getValue()
                                + "]");
                        if (StringUtils
                                .isNotBlank(z01.getMarcadorBiologico(i).getAlternateIdentifier().getValue())) {
                            try {
                                logger.debug("               Procesando VALOR DE MARCADOR BIOLOGICO ("
                                        + z01.getMarcadorBiologico(i).getAlternateIdentifier().getValue() + ") "
                                        + z01.getMarcadorBiologico(i).getAlternateText().getValue());
                                ValMarcaBioExt valMarcaBioExt = new ValMarcaBioExt();
                                valMarcaBioExt.setCentros(centros);
                                valMarcaBioExt.setCodValMarcaBioExt(
                                        z01.getMarcadorBiologico(i).getAlternateIdentifier().getValue()); //Z01.3.4
                                valMarcaBioExt.setTxtValMarcaBioExt(
                                        z01.getMarcadorBiologico(i).getAlternateText().getValue()); //Z01.3.5
                                valMarcaBioExt = valMarcaBioExtService
                                        .traducirEquivalenciaAndInsert(valMarcaBioExt);
                                logger.debug("                    Z01.3.(4,5) - Valor de Marcador Biologico: "
                                        + valMarcaBioExt.toString());

                                EpiValMarcaBio epiValMarcaBio = new EpiValMarcaBio();
                                epiValMarcaBio.setEpiMarcaBio(epiMarcaBio);
                                epiValMarcaBio.setValMarcaBio(valMarcaBioExt.getValMarcaBio());
                                epiValMarcaBios.add(epiValMarcaBio);
                            } catch (NoExisteEquivalenciaException neee) {
                                if (acuerdos != null) {
                                    if (acuerdos.getAcuMarcaBios() != null
                                            && !acuerdos.getAcuMarcaBios().isEmpty()) { //Es un criterio de inclusion del acuerdo
                                        if (StringUtils.isNotBlank(z01.getMarcadorBiologico(i)
                                                .getAlternateIdentifier().getValue())) {
                                            logger.error(
                                                    "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.3.(4,5) - VALOR DE MARCADOR BIOLOGICO ("
                                                            + z01.getMarcadorBiologico(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getMarcadorBiologico(i)
                                                                    .getAlternateText().getValue());
                                            resultado.add(
                                                    "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: VALOR DE MARCADOR BIOLOGICO ("
                                                            + z01.getMarcadorBiologico(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getMarcadorBiologico(i)
                                                                    .getAlternateText().getValue());
                                        } else {
                                            logger.error(
                                                    "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo Z01.3.(4,5) - VALOR DE MARCADOR BIOLOGICO");
                                            resultado.add(
                                                    "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: VALOR DE MARCADOR BIOLOGICO");
                                        }
                                    } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                                        if (StringUtils.isNotBlank(z01.getMarcadorBiologico(i)
                                                .getAlternateIdentifier().getValue())) {
                                            logger.error(
                                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.3.(4,5) - VALOR DE MARCADOR BIOLOGICO ("
                                                            + z01.getMarcadorBiologico(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getMarcadorBiologico(i)
                                                                    .getAlternateText().getValue());
                                            resultado.add(
                                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: VALOR DE MARCADOR BIOLOGICO ("
                                                            + z01.getMarcadorBiologico(i)
                                                                    .getAlternateIdentifier().getValue()
                                                            + ") " + z01.getMarcadorBiologico(i)
                                                                    .getAlternateText().getValue());
                                        }
                                    }
                                }
                            }
                        } else if (StringUtils.isNotBlank(
                                z01.getMarcadorBiologico(i).getNameOfAlternateCodingSystem().getValue())) {
                            logger.debug("               Procesando VALOR DE MARCADOR BIOLOGICO ("
                                    + z01.getMarcadorBiologico(i).getNameOfAlternateCodingSystem().getValue()
                                    + ")");
                            EpiValMarcaBio epiValMarcaBio = new EpiValMarcaBio();
                            epiValMarcaBio.setEpiMarcaBio(epiMarcaBio);
                            epiValMarcaBio.setValor(
                                    z01.getMarcadorBiologico(i).getNameOfAlternateCodingSystem().getValue());
                            epiValMarcaBios.add(epiValMarcaBio);
                        }

                        epiMarcaBio.setEpiValMarcaBios(epiValMarcaBios);
                    } catch (NoExisteEquivalenciaException neee) {
                        if (acuerdos != null) {
                            if (acuerdos.getAcuMarcaBios() != null && !acuerdos.getAcuMarcaBios().isEmpty()) { //Es un criterio de inclusion del acuerdo
                                if (StringUtils
                                        .isNotBlank(z01.getMarcadorBiologico(i).getIdentifier().getValue())) {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.3.(1,2) - MARCADOR BIOLOGICO ("
                                                    + z01.getMarcadorBiologico(i).getIdentifier().getValue()
                                                    + ") " + z01.getMarcadorBiologico(i).getText().getValue());
                                    resultado.add(
                                            "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: MARCADOR BIOLOGICO ("
                                                    + z01.getMarcadorBiologico(i).getIdentifier().getValue()
                                                    + ") " + z01.getMarcadorBiologico(i).getText().getValue());
                                } else {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo Z01.3.(1,2) - MARCADOR BIOLOGICO");
                                    resultado.add(
                                            "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: MARCADOR BIOLOGICO");
                                }
                            } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                                if (StringUtils
                                        .isNotBlank(z01.getMarcadorBiologico(i).getIdentifier().getValue())) {
                                    logger.error(
                                            "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo Z01.3.(1,2) - MARCADOR BIOLOGICO ("
                                                    + z01.getMarcadorBiologico(i).getIdentifier().getValue()
                                                    + ") " + z01.getMarcadorBiologico(i).getText().getValue());
                                    resultado.add(
                                            "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: MARCADOR BIOLOGICO ("
                                                    + z01.getMarcadorBiologico(i).getIdentifier().getValue()
                                                    + ") " + z01.getMarcadorBiologico(i).getText().getValue());
                                }
                            }
                        }
                    }
                }
            }

            //RXD.21 - Programas y Diagnosticos
            ProgramasExt programasExt = new ProgramasExt();
            Diagnosticos diagnosticos = null;
            for (int i = 0; i < rxd.getIndication().length; i++) {
                if (StringUtils.equalsIgnoreCase(rxd.getIndication(i).getNameOfCodingSystem().getValue(),
                        "I9C")) { //RXD.21 - Diagnostico
                    logger.debug("     Procesando datos del DIAGNOSTICO ("
                            + rxd.getIndication(i).getIdentifier().getValue() + ") "
                            + rxd.getIndication(i).getText().getValue());
                    try {
                        diagnosticos = new Diagnosticos();
                        diagnosticos.setCodDiagnostico(rxd.getIndication(i).getIdentifier().getValue()); //RXD.21.1
                        diagnosticos.setTxtDiagnostico(rxd.getIndication(i).getText().getValue()); //RXD.21.2
                        diagnosticos = diagnosticosService.findByCodDiagnostico(diagnosticos);
                        logger.debug("          RXD.21(I9C) - Diagnostico: " + diagnosticos.toString());
                    } catch (NoResultException nre) {
                        diagnosticos = null;
                        if (acuerdos != null) {
                            if (acuerdos.getAcuDiagnosticoses() != null
                                    && !acuerdos.getAcuDiagnosticoses().isEmpty()) { //Es un criterio de inclusion del acuerdo
                                if (StringUtils.isNotBlank(rxd.getIndication(i).getIdentifier().getValue())) {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo RXD.21(I9C) - DIAGNOSTICO ("
                                                    + rxd.getIndication(i).getIdentifier().getValue() + ") "
                                                    + rxd.getIndication(i).getText().getValue());
                                    resultado.add(
                                            "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: DIAGNOSTICO ("
                                                    + rxd.getIndication(i).getIdentifier().getValue() + ") "
                                                    + rxd.getIndication(i).getText().getValue());
                                } else {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo RXD.21(I9C) - DIAGNOSTICO");
                                    resultado.add(
                                            "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: DIAGNOSTICO");
                                }
                            }
                        }
                    }
                } else if (StringUtils.equalsIgnoreCase(rxd.getIndication(i).getNameOfCodingSystem().getValue(),
                        "PRDSP")) { //RXD.21 - Programa
                    logger.debug("     Procesando datos del PROGRAMA ("
                            + rxd.getIndication(i).getIdentifier().getValue() + ") "
                            + rxd.getIndication(i).getText().getValue());
                    try {
                        programasExt.setCentros(centros);
                        programasExt.setCodProgramaExt(rxd.getIndication(i).getIdentifier().getValue()); //RXD.21.1
                        programasExt.setTxtProgramaExt(rxd.getIndication(i).getText().getValue()); //RXD.21.2
                        programasExt = programasExtService.traducirEquivalenciaAndInsert(programasExt);
                        logger.debug("          RXD.21(PRDSP) - PROGRAMA: " + programasExt.toString());
                    } catch (NoExisteEquivalenciaException neee) {
                        if (acuerdos != null) {
                            if (acuerdos.getAcuProgramases() != null
                                    && !acuerdos.getAcuProgramases().isEmpty()) { //Es un criterio de inclusion del acuerdo
                                if (StringUtils.isNotBlank(rxd.getIndication(i).getIdentifier().getValue())) {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo RXD.21(PRDSP) - PROGRAMA ("
                                                    + rxd.getIndication(i).getIdentifier().getValue() + ") "
                                                    + rxd.getIndication(i).getText().getValue());
                                    resultado.add(
                                            "No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: PROGRAMA ("
                                                    + rxd.getIndication(i).getIdentifier().getValue() + ") "
                                                    + rxd.getIndication(i).getText().getValue());
                                } else {
                                    logger.error(
                                            "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo RXD.21(PRDSP) - PROGRAMA");
                                    resultado.add(
                                            "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: PROGRAMA");
                                }
                            } else if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                                if (StringUtils.isNotBlank(rxd.getIndication(i).getIdentifier().getValue())) {
                                    logger.error(
                                            "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el criterio de inclusion en el campo RXD.21(PRDSP) - PROGRAMA ("
                                                    + rxd.getIndication(i).getIdentifier().getValue() + ") "
                                                    + rxd.getIndication(i).getText().getValue());
                                    resultado.add(
                                            "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CRITERIO DE INCLUSION: PROGRAMA ("
                                                    + rxd.getIndication(i).getIdentifier().getValue() + ") "
                                                    + rxd.getIndication(i).getText().getValue());
                                }
                            }
                        }
                    }
                }
            }

            //PID.7 - Edad (Fecha de Nacimiento)
            Date fechaNacimiento = null;
            logger.debug("     Procesando datos de la EDAD (Fecha de Nacimiento) ("
                    + pid.getDateTimeOfBirth().getTime().getValue() + ")");
            try {
                fechaNacimiento = pid.getDateTimeOfBirth().getTime().getValueAsDate(); //PID.7
                if (fechaNacimiento == null) {
                    throw new Exception("No se ha indicado la fecha de nacimiento");
                }
            } catch (Exception e) {
                if (acuerdos != null) {
                    if (acuerdos.getAcuEdadeses() != null && !acuerdos.getAcuEdadeses().isEmpty()) { //Es un criterio de inclusion del acuerdo
                        logger.error(
                                "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo PID.7 - EDAD[Fecha de Nacimiento] ("
                                        + pid.getDateTimeOfBirth().getTime().getValue() + ")");
                        resultado.add(
                                "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: EDAD [Fecha de Nacimiento]");
                    }
                }
            }

            //OBX.3 - Peso
            Double peso = null;
            logger.debug("     Procesando datos del PESO ("
                    + obx.getObservationIdentifier().getText().getValue() + ")");
            try {
                peso = NumberUtils.toDouble(obx.getObservationIdentifier().getText().getValue()); //OBX.3
                if (peso == null) {
                    throw new Exception("No se ha indicado el peso");
                }
            } catch (Exception e) {
                if (acuerdos != null) {
                    if (acuerdos.getAcuPesoses() != null && !acuerdos.getAcuPesoses().isEmpty()) { //Es un criterio de inclusion del acuerdo
                        logger.error(
                                "               No se puede procesar el movimiento sin INFORMACION para el criterio de inclusion en el campo OBX.3 - PESO ("
                                        + obx.getObservationIdentifier().getText().getValue() + ")");
                        resultado.add(
                                "No se puede procesar el movimiento sin INFORMACION para el CRITERIO DE INCLUSION: PESO");
                    }
                }
            }

            //MAESTROS GENERALES
            //Z01.1 - Tipo de Uso
            logger.debug("     Procesando datos del TIPO DE USO (" + z01.getTipoUso().getIdentifier().getValue()
                    + ") " + z01.getTipoUso().getText().getValue());
            TiposUsoExt tiposUsoExt = new TiposUsoExt();
            try {
                tiposUsoExt.setCentros(centros);
                tiposUsoExt.setCodTipoUsoExt(z01.getTipoUso().getIdentifier().getValue()); //Z01.1.1
                tiposUsoExt.setTxtTipoUsoExt(z01.getTipoUso().getText().getValue()); //Z01.1.2
                tiposUsoExt = tiposUsoExtService.traducirEquivalenciaAndInsert(tiposUsoExt);
                logger.debug("          Z01.1 - Tipo de Uso: " + tiposUsoExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getTipoUso().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO Z01.6 - TIPO DE USO ("
                                            + z01.getTipoUso().getIdentifier().getValue() + ") "
                                            + z01.getTipoUso().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: TIPO DE USO ("
                                            + z01.getTipoUso().getIdentifier().getValue() + ") "
                                            + z01.getTipoUso().getText().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());
            }

            //RXD.5 - Formas Farmaceutica
            logger.debug("     Procesando la FORMA FARMACEUTICA DE LA DOSIS DISPENSADA ("
                    + rxd.getActualDispenseUnits().getIdentifier().getValue() + ") "
                    + rxd.getActualDispenseUnits().getText().getValue());
            FormasFarExt formasFarExt = new FormasFarExt();
            try {
                formasFarExt.setCentros(centros);
                formasFarExt.setCodFormaFarExt(rxd.getActualDispenseUnits().getIdentifier().getValue()); //RXD.5.1
                formasFarExt.setTxtFormaFarExt(rxd.getActualDispenseUnits().getText().getValue()); //RXD.5.2
                formasFarExt = formasFarExtService.traducirEquivalenciaAndInsert(formasFarExt);
                logger.debug("          RXD.5 - Forma Farmaceutica de la Dosis Dispensada: "
                        + formasFarExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(rxd.getActualDispenseUnits().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO RXD.5 - FORMA FARMACEUTICA("
                                            + rxd.getActualDispenseUnits().getIdentifier().getValue() + ") "
                                            + rxd.getActualDispenseUnits().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO.No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: FORMA FARMACEUTICA ("
                                            + rxd.getActualDispenseUnits().getIdentifier().getValue() + ") "
                                            + rxd.getActualDispenseUnits().getText().getValue());
                        }
                    }
                }
            }

            //Z01.7 - Protocolos
            logger.debug("     Procesando datos del PROTOCOLO (" + z01.getProtocolo().getIdentifier().getValue()
                    + ") " + z01.getProtocolo().getText().getValue());
            ProtocolosExt protocolosExt = new ProtocolosExt();
            try {
                protocolosExt.setCentros(centros);
                protocolosExt.setCodProtocoloExt(z01.getProtocolo().getIdentifier().getValue()); //Z01.7.1
                protocolosExt.setTxtProtocoloExt(z01.getProtocolo().getText().getValue()); //Z01.7.2
                protocolosExt = protocolosExtService.traducirEquivalenciaAndInsert(protocolosExt);
                logger.debug("          Z01.7 - Protocolo: " + protocolosExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getProtocolo().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO.No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO Z01.7 - PROTOCOLO ("
                                            + z01.getProtocolo().getIdentifier().getValue() + ") "
                                            + z01.getProtocolo().getText().getValue());
                            resultado.add(
                                    "EL ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: PROTOCOLO ("
                                            + z01.getProtocolo().getIdentifier().getValue() + ") "
                                            + z01.getProtocolo().getText().getValue());
                        }
                    }
                }
            }

            //Z01.8 - Servicios
            logger.debug("     Procesando datos del SERVICIO (" + z01.getServicio().getIdentifier().getValue()
                    + ") " + z01.getServicio().getText().getValue());
            ServiciosExt serviciosExt = new ServiciosExt();
            try {
                serviciosExt.setCentros(centros);
                serviciosExt.setCodServicioExt(z01.getServicio().getIdentifier().getValue()); //Z01.8.1
                serviciosExt.setTxtServicioExt(z01.getServicio().getText().getValue()); //Z01.8.2
                serviciosExt = serviciosExtService.traducirEquivalenciaAndInsert(serviciosExt);
                logger.debug("          Z01.8 - Servicio: " + serviciosExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getServicio().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO Z01.8 - SERVICIO ("
                                            + z01.getServicio().getIdentifier().getValue() + ") "
                                            + z01.getServicio().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: SERVICIO ("
                                            + z01.getServicio().getIdentifier().getValue() + ") "
                                            + z01.getServicio().getText().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 (acuerdos != null) {
                    if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getUnidMedDosisPrescrita().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO Z01.10 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                            + z01.getUnidMedDosisPrescrita().getIdentifier().getValue() + ") "
                                            + z01.getUnidMedDosisPrescrita().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: 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.15.1
                secuenciasExt.setTxtSecuenciaExt(z01.getSecuencia().getText().getValue()); //Z01.15.2
                secuenciasExt = secuenciasExtService.traducirEquivalenciaAndInsert(secuenciasExt);
                logger.debug("          Z01.13 - Secuencia: " + secuenciasExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getSecuencia().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO Z01.15 - SECUENCIA ("
                                            + z01.getSecuencia().getIdentifier().getValue() + ") "
                                            + z01.getSecuencia().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: 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.16.1
                pautasExt.setTxtPautaExt(z01.getPauta().getText().getValue()); //Z01.16.2
                pautasExt = pautasExtService.traducirEquivalenciaAndInsert(pautasExt);
                logger.debug("          Z01.14 - Pauta: " + pautasExt.toString());
            } catch (NoExisteEquivalenciaException neee) {
                if (acuerdos != null) {
                    if (StringUtils.equals(acuerdos.getRequerido(), "S")) {
                        if (StringUtils.isNotBlank(z01.getPauta().getIdentifier().getValue())) {
                            logger.error(
                                    "               El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO Z01.14 - PAUTA ("
                                            + z01.getPauta().getIdentifier().getValue() + ") "
                                            + z01.getPauta().getText().getValue());
                            resultado.add(
                                    "El ACUERDO es REQUERIDO. No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: PAUTA ("
                                            + z01.getPauta().getIdentifier().getValue() + ") "
                                            + z01.getPauta().getText().getValue());
                        }
                    }
                }
            }

            //OTRAS VALIDACIONES SIN NORMALIZACION
            //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() + ")");
            }

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

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

            //RXD.4 - Dosis Dispensada en Forma Farmaceutica
            Double dosis_dispensada = null;
            logger.debug("     Procesando datos de la DOSIS DISPENSADA ("
                    + rxd.getActualDispenseAmount().getValue() + ")");
            if (StringUtils.isNotBlank(rxd.getActualDispenseAmount().getValue())
                    && NumberUtils.isNumber(rxd.getActualDispenseAmount().getValue())) {
                try {
                    dosis_dispensada = NumberUtils.createDouble(rxd.getActualDispenseAmount().getValue());
                    logger.debug("          RXD.4 - Dosis Dispensada: " + dosis_dispensada);
                } catch (Exception e) {
                    resultado.add(
                            "No se puede procesar el movimiento porque los datos en el campo RXD.4 - DOSIS PRESCRITA ("
                                    + rxd.getActualDispenseAmount().getValue() + ") NO son correctos");
                }
            } else {
                logger.error(
                        "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: RXD.4 - DOSIS PRESCRITA ("
                                + rxd.getActualDispenseAmount().getValue() + ")");
                resultado
                        .add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: DOSIS PRESCRITA ("
                                + rxd.getActualDispenseAmount().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 INFORMACION 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.11 - Ciclo
            String ciclo = null;
            logger.debug("     Procesando datos de CICLO (" + z01.getCiclo().getValue() + ")");
            if (StringUtils.isNotBlank(z01.getCiclo().getValue())) {
                ciclo = z01.getCiclo().getValue();
                logger.debug("          Z01.11 - Ciclo: " + ciclo);
            }

            //Z01.12 - Dia Ciclo
            String dia_ciclo = null;
            logger.debug("     Procesando datos del DIA DE CICLO (" + z01.getDiaCiclo().getValue() + ")");
            if (StringUtils.isNotBlank(z01.getDiaCiclo().getValue())) {
                dia_ciclo = z01.getDiaCiclo().getValue();
                logger.debug("          Z01.12 - Dia de Ciclo: " + dia_ciclo);
            }

            //CONSULTA EMPI
            if (MPRConstantes._EMPI_ENABLE) {
                try {
                    logger.debug("          Iniciando consulta EMPI (Usuario: " + MPRConstantes._EMPI_USUARIO
                            + ", Sistema: " + MPRConstantes._EMPI_SISTEMA + ", URL: " + MPRConstantes._EMPI_URL
                            + ")");
                    EMPIClient client = new EMPIClient(MPRConstantes._EMPI_USUARIO, MPRConstantes._EMPI_SISTEMA,
                            MPRConstantes._EMPI_URL);
                    logger.debug("               Obteniendo Registros por CIPA: (CIPA: " + pacientes.getCipa()
                            + ")");
                    EMPIResponse response = client.obtenerRegistrosByCIPA(pacientes.getCipa());
                    if (response != null && response.getPaciente() != null) {
                        logger.debug("               Respuesta obtenida: " + response.toString());

                        pacientes.setTxtNombre(response.getPaciente().getNombre());
                        pacientes.setTxtApellido1(response.getPaciente().getApellido1());
                        pacientes.setTxtApellido2(response.getPaciente().getApellido2());
                        fechaNacimiento = response.getPaciente().getFechaNacimiento().toGregorianCalendar()
                                .getTime();
                    } else {
                        logger.debug(
                                "          No se han obtenido datos de EMPI. Se emplearan los datos del mensaje HL7");
                    }
                } catch (Exception e) {
                    logger.warn(
                            "Se han producido errores al obtener datos de EMPI. Se emplearan los datos del mensaje HL7: "
                                    + e.getMessage());
                }
            }

            //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() + ")");
                if (StringUtils.isNotBlank(pacientes.getCipa())) {
                    pacientes = pacientesService.findByCIPA(pacientes);
                } else {
                    Episodios consulta = new Episodios();
                    consulta.setNhc(nhc);
                    consulta.setCentros(centros);
                    consulta = episodiosService.findByNHCIdCentro(consulta);
                    pacientes = consulta.getPacientes();
                }
            } catch (NoResultException nre) {
                logger.debug("          Almacenando datos del PACIENTE");
                pacientes.setSexos(sexosExt.getSexos());
                pacientes.setFechaNac(fechaNacimiento);
                pacientes = pacientesService.save(pacientes);
            } finally {
                logger.debug("          Paciente: " + pacientes.toString());
            }

            //EPISODIO
            try {
                episodios.setNhc(nhc);
                episodios.setCentros(centros);
                episodios.setCodEpisodio(cod_episodio);
                episodios.setPacientes(pacientes);
                episodios.setProgramas(programasExt.getProgramas());
                episodios.setServicio(serviciosExt.getServicios());

                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 {
                if (contador == 0) { //Solo la primera vez
                    //EPI_MARCA_BIO y EPI_VAL_MARCA_BIO
                    epiMarcaBioService.delete(episodios.getEpiMarcaBios());
                    if (epiMarcaBios != null && !epiMarcaBios.isEmpty()) {
                        for (EpiMarcaBio epiMarcaBio : epiMarcaBios) {
                            logger.debug(
                                    "               Insertando Marcador Biologico: " + epiMarcaBio.toString());
                            epiMarcaBio.setEpisodios(episodios);
                            epiMarcaBioService.save(epiMarcaBio);
                        }
                    }

                    //EPI_SIT_CLINICA y EPI_VAL_SIT_CLINICA
                    epiSitClinicaService.delete(episodios.getEpiSitClinicas());
                    if (epiSitClinicas != null && !epiSitClinicas.isEmpty()) {
                        for (EpiSitClinica epiSitClinica : epiSitClinicas) {
                            logger.debug(
                                    "               Insertando Situacion Clinica: " + epiSitClinica.toString());
                            epiSitClinica.setEpisodios(episodios);
                            epiSitClinicaService.save(epiSitClinica);
                        }
                    }
                }
                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(), "-")[8],
                            StringUtils.split(prescripciones.getCodPrescripcion(), "-")[8])) {
                        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.setUnidMed(unidMedExt.getUnidMed());
                prescripciones.setFechaIni(fecha_ini_prescripcion);
                prescripciones.setPautas(pautasExt.getPautas());
                prescripciones.setSecuencias(secuenciasExt.getSecuencias());
                prescripciones = prescripcionesService.save(prescripciones);
            } finally {
                logger.debug("          Prescripcion: " + prescripciones.toString());
            }

            //DISPENSACIONES
            logger.debug("     Almacenando datos de la DISPENSACION: (" + cod_dispensacion + ")");
            Dispensaciones dispensaciones = new Dispensaciones();
            try {
                dispensaciones.setCodDispensacion(cod_dispensacion);
                logger.debug("          Buscando DISPENSACION por COD_DISPENSACION ("
                        + dispensaciones.getCodDispensacion() + ")");
                dispensaciones = findByCodDispensacion(dispensaciones);
                dispensaciones.setCantidad(dosis_dispensada);
                logger.debug(
                        "          Actualizando CANTIDAD DISPENSADA de la DISPENSACION con COD_DISPENSACION ("
                                + dispensaciones.getCodDispensacion() + ")");
            } catch (NoResultException nre) {
                dispensaciones.setAcuerdos(acuerdos);
                dispensaciones.setPrescripciones(prescripciones);
                dispensaciones.setCantidad(dosis_dispensada);
                dispensaciones.setFormasFar(formasFarExt.getFormasFar());
                dispensaciones.setFechaDisp(fecha_dispensacion);
                dispensaciones.setDiagnosticos(diagnosticos);
                dispensaciones.setIndicaciones(indicacionesExt.getIndicaciones());
                dispensaciones.setLineasTrat(lineasTratExt.getLineasTrat());
                dispensaciones.setProtocolos(protocolosExt.getProtocolos());
                dispensaciones.setTiposUso(tiposUsoExt.getTiposUso());
                dispensaciones.setPeso(peso);
                dispensaciones.setCiclo(ciclo);
                dispensaciones.setDiaCiclo(dia_ciclo);
                logger.debug("          Insertando nueva DISPENSACION con COD_DISPENSACION ("
                        + dispensaciones.getCodDispensacion() + ")");
            } finally {
                dispensaciones = save(dispensaciones);
                logger.debug("          Dispensacion: " + dispensaciones.toString());
            }
            contador++;
            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());
    }
}