Example usage for java.math BigDecimal toBigInteger

List of usage examples for java.math BigDecimal toBigInteger

Introduction

In this page you can find the example usage for java.math BigDecimal toBigInteger.

Prototype

public BigInteger toBigInteger() 

Source Link

Document

Converts this BigDecimal to a BigInteger .

Usage

From source file:org.kalypso.model.wspm.tuhh.core.wprof.BCEShapeWPRofContentProvider.java

private <T> T toNumber(final BigDecimal in, final Class<T> outType) {
    if (Byte.class == outType)
        return outType.cast(in.byteValue());
    if (Short.class == outType)
        return outType.cast(in.shortValue());
    if (Integer.class == outType)
        return outType.cast(in.intValue());
    if (Long.class == outType)
        return outType.cast(in.longValue());
    if (Float.class == outType)
        return outType.cast(in.floatValue());
    if (Double.class == outType)
        return outType.cast(in.doubleValue());

    if (BigInteger.class == outType)
        return outType.cast(in.toBigInteger());

    return outType.cast(in);
}

From source file:com.aegiswallet.actions.MainActivity.java

public void notifyCoinsReceivedOrSent(Double amount, boolean received) {
    final NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this);

    String eventTitle = "";
    String eventLocation = "";
    String eventDescription = "";
    int wearIcon = 0;

    BigDecimal decimal = BigDecimal.valueOf(amount);
    BigInteger amountBigInt = decimal.toBigInteger();

    if (received) {
        notification.setSmallIcon(R.drawable.aegis_receive_icon);
        notification.setContentText(getString(R.string.received_string) + " "
                + BasicUtils.satoshiToBTC(amountBigInt) + getString(R.string.btc_string));

        eventTitle = "Aegis Receive";
        eventLocation = "Aegis Wallet";
        eventDescription = getString(R.string.received_string) + " " + BasicUtils.satoshiToBTC(amountBigInt)
                + getString(R.string.btc_string);
        wearIcon = R.drawable.aegis_receive_icon;

    } else if (!received) {
        notification.setSmallIcon(R.drawable.aegis_send_icon);
        notification.setContentText(getString(R.string.sent_string) + " "
                + BasicUtils.satoshiToBTC(amountBigInt) + getString(R.string.btc_string));

        eventTitle = "Aegis Send";
        eventLocation = "Aegis Wallet";
        eventDescription = getString(R.string.sent_string) + " " + BasicUtils.satoshiToBTC(amountBigInt)
                + getString(R.string.btc_string);
        wearIcon = R.drawable.aegis_send_icon;
    }/*from w  w  w  .j a  v  a 2  s  .c  o m*/
    notification.setContentTitle(getString(R.string.app_name));

    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,
            new Intent(MainActivity.this, MainActivity.class), 0);

    notification.setContentIntent(pendingIntent);
    notification.setOngoing(false);
    notificationManager.notify(1, notification.getNotification());

    NotificationCompat.BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
    bigStyle.bigText(eventDescription);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.initpageicon))
            .setContentTitle(eventTitle).setContentText(eventLocation).setContentIntent(pendingIntent)
            .setStyle(bigStyle);

}

From source file:jp.terasoluna.fw.web.struts.form.FieldChecksEx.java

/**
 * wtB?[h?l`FbN?B//from   w w  w .  j  ava  2s .  c o  m
 * 
 * ?Ap?A<code>BigDecimal</code> ^??
 * ??s\G?[pActionMessage???A<code>false</code> p?B
 * 
 * ???w???A?mF?s?B <code>validation.xml</code> 
 * <code>isAccordedInteger()</code>  <code>"true"</code> w??
 * ???`FbN?s?B `FbN???AG?[pActionMessage???Afalsep?B
 * 
 * ????w???A?mF?s?B
 * validation.xmlisAccordedScale"true"?? ???`FbN?s?B
 * 
 * <p>
 * G?[???AG?[????A wG?[?Xg?B G?[?bZ?[WtH?[}bg?A<code>validation-rules.xml</code>
 * L?q?B<br>
 * L?A??3?A??2?l??B
 * </p>
 * 
 * <h5>validation.xmlL?q</h5>
 * <code><pre>
 * &lt;form name=&quot;/sample&quot;&gt;
 *  ?E?E?E
 *  &lt;field property=&quot;escape&quot;
 *      depends=&quot;number&quot;&gt;
 *    &lt;arg0 key=&quot;sample.escape&quot;/&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;integerLength&lt;/var-name&gt;
 *      &lt;var-value&gt;3&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;scale&lt;/var-name&gt;
 *      &lt;var-value&gt;2&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedInteger&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedScale&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *  &lt;/field&gt;
 *  ?E?E?E
 * &lt;/form&gt;
 * </pre></code>
 * <h5>validation.xml?v&lt;var&gt;vf</h5>
 * <table border="1">
 * <tr>
 * <td><center><b><code>var-name</code></b></center></td>
 * <td><center><b><code>var-value</code></b></center></td>
 * <td><center><b>K?{?</b></center></td>
 * <td><center><b>Tv</b></center></td>
 * </tr>
 * <tr>
 * <td> <code>integerLength</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>?????A<code>isAccordedInteger</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>scale</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>??l???A<code>isAccordedScale</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedInteger</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedScale</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * </table>
 * 
 * @param bean
 *            ??IuWFNg
 * @param va
 *            StrutspValidatorAction
 * @param field
 *            tB?[hIuWFNg
 * @param errors
 *            ActionMessages ANVG?[
 * @param validator
 *            ValidatorCX^X
 * @param request
 *            HTTPNGXg
 * @return l? <code>true</code>
 */
public static boolean validateNumber(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        Validator validator, HttpServletRequest request) {

    // beannull?AG?[?O?o?Atruep?B
    if (bean == null) {
        log.error("bean is null.");
        return true;
    }
    // ???
    String integerLength = field.getVarValue("integerLength");
    // ???
    String scaleStr = field.getVarValue("scale");
    // ???v`FbN
    String isAccordedInteger = field.getVarValue("isAccordedInteger");
    // ???v`FbN
    String isAccordedScale = field.getVarValue("isAccordedScale");

    String value = null;
    if (isString(bean)) {
        value = (String) bean;
    } else {
        value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    }
    // ?lnull?Atruep
    if (GenericValidator.isBlankOrNull(value)) {
        return true;
    }
    char[] chars = value.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (!isHankaku(chars[i])) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }
    // ???w???A??`FbN?s
    if (GenericValidator.isInt(integerLength)) {
        try {
            BigDecimal bd = new BigDecimal(value);
            // ???l?o
            BigInteger bi = bd.toBigInteger().abs();
            // ???
            int length = bi.toString().length();
            // validation.xmlw?
            int checkLength = Integer.valueOf(integerLength).intValue();
            // ?I?[o?Afalsep
            if (length > checkLength) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
            // vw
            if (isAccordedInteger != null && "true".equals(isAccordedInteger)) {
                // ?sv?Afalsep
                if (length != checkLength) {
                    errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                    return false;
                }
            }
        } catch (NumberFormatException nfe) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }

    // ???w???A??`FbN?s
    if (GenericValidator.isInt(scaleStr)) {
        int scale = 0;
        int checkScale = 0;
        try {
            BigDecimal bd = new BigDecimal(value);
            scale = bd.scale();
            // validation.xmlw?
            checkScale = Integer.valueOf(scaleStr).intValue();
        } catch (NumberFormatException e) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // ?I?[o?Afalsep
        if (scale > checkScale) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // vw
        if (isAccordedScale != null && "true".equals(isAccordedScale)) {
            // ?sv?Afalsep
            if (scale != checkScale) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
        }
    }
    return true;
}

From source file:org.kuali.coeus.propdev.impl.print.NIHResearchAndRelatedXmlStream.java

private BigInteger getNSFProjectDuration(DevelopmentProposal developmentProposal) {

    BigInteger projectDuration = null;
    if (developmentProposal.getRequestedEndDateInitial() != null
            && developmentProposal.getRequestedStartDateInitial() != null) {
        BigDecimal months = getMonthsBetweenDates(developmentProposal.getRequestedStartDateInitial(),
                developmentProposal.getRequestedEndDateInitial());
        projectDuration = months.toBigInteger();
    }//w  w  w  . j  a v  a 2s.co  m
    return projectDuration;
}

From source file:uk.ac.ebi.arrayexpress.utils.saxon.search.AbstractIndexEnvironment.java

public Document processEntryIndex(Object node, Configuration config, XPathQueryService service,
        Map<String, XPathExpression> fieldXpe) throws Exception {
    Document luceneDoc = new Document();
    XPath xp = new XPathEvaluator(config);
    for (FieldInfo field : fields.values()) {
        try {//from w w  w  .ja va  2s  .c om
            if (!field.process) {
                List values = (List) fieldXpe.get(field.name).evaluate(node, XPathConstants.NODESET);
                for (Object v : values) {

                    if ("integer".equals(field.type)) {
                        addIntIndexField(luceneDoc, field.name, v, field.shouldStore, field.shouldSort);

                    } else if ("date".equals(field.type)) {
                        // todo:
                        // addDateIndexField(d,
                        // field.name,
                        // v);
                        logger.error("Date fields are not supported yet, field [{}] will not be created",
                                field.name);
                    } else if ("boolean".equals(field.type)) {
                        addBooleanIndexField(luceneDoc, field.name, v, field.shouldSort);
                    } else {
                        addIndexField(luceneDoc, field.name, v, field.shouldAnalyze, field.shouldStore,
                                field.shouldSort);
                    }
                }

            } else {
                if (field.name.equalsIgnoreCase("attributes")) {
                    // implement here the biosamples
                    // database sample attributes
                    // logic
                    // TODO: rpe
                    // logger.debug("There is A special treatment for this field->"
                    // + field.name);
                    List values = (List) fieldXpe.get(field.name).evaluate(node, XPathConstants.NODESET);

                    for (Iterator iterator = values.iterator(); iterator.hasNext();) {
                        Object object = (Object) iterator.next();
                        // logger.debug("attributes->" + object);
                        String valClass = (String) fieldXpe.get("attributeName").evaluate(object,
                                XPathConstants.STRING);
                        //TODO: document this on trac and on website documentations help
                        valClass = valClass.replace(" ", "_").toLowerCase();
                        //valClass=valClass.toLowerCase();
                        String valType = (String) fieldXpe.get("attributeType").evaluate(object,
                                XPathConstants.STRING);
                        String valValue = (String) fieldXpe.get("attributeValue").evaluate(object,
                                XPathConstants.STRING);

                        if (!valType.equalsIgnoreCase("integer") && !valType.equalsIgnoreCase("real")) {
                            //TODO: change this value
                            valValue = valValue.substring(0, Math.min(valValue.length(), 25));
                            addIndexField(luceneDoc, "attributes", "=" + valClass + "= " + valValue, true,
                                    false, true);
                        } else {

                            valValue = valValue.trim();
                            int val = 0;
                            if (valValue == null || valValue.equalsIgnoreCase("")
                                    || valValue.equalsIgnoreCase("NaN")) {
                                valValue = "0";
                            }
                            BigDecimal num = new BigDecimal(valValue);
                            num = num.multiply(new BigDecimal(100));
                            int taux = num.toBigInteger().intValue();
                            valValue = String.format("%07d", taux);
                            //I need to mantain the spaces for lucene consider different words
                            addIndexField(luceneDoc, "attributes", "=" + valClass + "= " + valValue, true,
                                    false, true);
                        }
                        //                     logger.debug("@class->" + valClass);
                        //                     logger.debug("@type->" + valType);
                        //                     logger.debug("text->" + valValue);
                    }
                } else {
                    // logger.debug("There is NO special treatment for this field->"
                    // + field.name);
                }
            }
        } catch (XPathExpressionException x) {
            String xmlError = PrintUtils.printNodeInfo((NodeInfo) node, config);
            logger.error("Field being processed->[{}]", field.name);
            xmlError = "##FIELD BEING PROCESSED##->" + field.name + "\n" + xmlError;
            logger.error("XPathExpressionException->[{}]", x.getMessage());
            logger.error("Caught an exception while indexing expression [" + field.path + "] for document ["
                    + ((NodeInfo) node).getStringValue().substring(0, 20) + "...]", x);

            throw new Exception("XPathExpressionException Xml:" + xmlError, x);
        } catch (Exception xe) {
            String xmlError = PrintUtils.printNodeInfo((NodeInfo) node, config);
            logger.error("Generic Exception->[{}]", xe.getMessage());
            throw new Exception("Generic Exception Xml:" + xmlError, xe);
        }
    }

    return luceneDoc;
}

From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = {
        "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "")
public void validateEnterAccountDetailsStep(ValidationContext context) {
    MessageContext messageContext = context.getMessageContext();

    Errors errors = validator.checkConstraints(this);

    // handle data binding errors that may of occurred
    if (messageContext.hasErrorMessages()) {
        Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() {

            @Override// w ww.ja va  2s  .c  om
            public boolean test(@SuppressWarnings("unused") Message message) {
                return true;
            }
        });
        messageContext.clearMessages();

        for (Message message : errorMessages) {
            handleDataMappingError(errors, message);
        }
    }

    if (this.glimApplicable) {
        int index = 0;
        int selectedCount = 0;
        for (Boolean clientSelected : this.clientSelectForGroup) {
            if (clientSelected != null && clientSelected.booleanValue()) {

                Number clientAmount = this.clientAmount[index];

                if (clientAmount == null
                        || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) {
                    String defaultErrorMessage = "Please specify valid Amount.";
                    rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage);
                }

                if (clientAmount != null) {
                    BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros();
                    int places = amountAsDecimal.scale();
                    if (places > this.digitsAfterDecimalForMonetaryAmounts) {
                        String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
                        rejectInterestRateFieldValue(errors, defaultErrorMessage,
                                "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid",
                                new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts });
                    }

                    int digitsBefore = amountAsDecimal.toBigInteger().toString().length();
                    if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) {
                        String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
                        rejectInterestRateFieldValue(errors, defaultErrorMessage,
                                "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid",
                                new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts });
                    }
                }

                // check error message of loan purpose for each client when its mandatory..
                Integer clientLoanPurposeId = this.clientLoanPurposeId[index];
                if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) {
                    errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid",
                            new Object[] { index + 1 }, "Please specify loan purpose.");
                    this.clientLoanPurposeId[index] = 0;
                } else {
                    // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over.
                    if (clientLoanPurposeId == null) {
                        this.clientLoanPurposeId[index] = 0;
                    }
                }

                selectedCount++;
            } else {

                Number clientAmount = this.clientAmount[index];
                Integer clientLoanPurposeId = this.clientLoanPurposeId[index];
                if (clientAmount != null || clientLoanPurposeId != null) {
                    String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan.";
                    rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage);
                }
            }

            index++;
        }

        if (selectedCount < 2) {
            String defaultErrorMessage = "Not enough clients for group loan.";
            rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage);
        }
    }

    if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) {
        String defaultErrorMessage = "Please specify valid Amount.";
        if (glimApplicable) {
            defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product.";
            rejectGlimTotalAmountField(errors, defaultErrorMessage);
        } else {
            rejectAmountField(errors, defaultErrorMessage);
        }
    }

    if (this.amount != null) {
        BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros();
        int places = amountAsDecimal.scale();
        if (places > this.digitsAfterDecimalForMonetaryAmounts) {
            String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.amount.digitsAfterDecimal.invalid",
                    new Object[] { this.digitsAfterDecimalForMonetaryAmounts });
        }

        int digitsBefore = amountAsDecimal.toBigInteger().toString().length();
        if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) {
            String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.amount.digitsBeforeDecimal.invalid",
                    new Object[] { this.digitsBeforeDecimalForMonetaryAmounts });
        }
    }

    if (this.interestRate == null
            || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) {
        String defaultErrorMessage = "Please specify valid Interest rate.";
        rejectInterestRateField(errors, defaultErrorMessage);
    }

    if (this.interestRate != null) {
        BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros();
        int places = interestRateAsDecimal.scale();
        if (places > this.digitsAfterDecimalForInterest) {
            String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.digitsAfterDecimalForInterest.invalid",
                    new Object[] { this.digitsAfterDecimalForInterest });
        }

        int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length();
        if (digitsBefore > this.digitsBeforeDecimalForInterest) {
            String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage,
                    "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid",
                    new Object[] { this.digitsBeforeDecimalForInterest });
        }
    }

    if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments,
            this.minNumberOfInstallments, this.maxNumberOfInstallments)) {
        String defaultErrorMessage = "Please specify valid number of installments.";
        rejectNumberOfInstallmentsField(errors, defaultErrorMessage);
    }

    if (this.graceDuration == null || this.graceDuration.intValue() < 0) {
        if (!errors.hasFieldErrors("graceDuration")) {
            String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than "
                    + numberOfInstallments.intValue() + ".";
            rejectGraceDurationField(errors, defaultErrorMessage);
        }
    } else {
        if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) {
            String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition.";
            errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid",
                    defaultErrorMessage);
        }

        if (this.numberOfInstallments != null
                && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) {
            String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments.";
            errors.rejectValue("graceDuration",
                    "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid",
                    defaultErrorMessage);
        }
    }

    if (dateValidator == null) {
        dateValidator = new DateValidator();
    }
    if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM,
            this.disbursementDateYY)) {
        String defaultErrorMessage = "Please specify valid disbursal date.";
        rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD",
                "loanAccountFormBean.DisbursalDate.invalid", "");
    } else {
        LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(),
                disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate();

        org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors();
        if (this.redoLoanAccount) {
            disbursementDateErrors = loanDisbursementDateValidationServiceFacade
                    .validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId);
        } else {
            disbursementDateErrors = loanDisbursementDateValidationServiceFacade
                    .validateLoanDisbursementDate(validDate, customerId, productId);
        }
        for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) {
            String defaultErrorMessage = "The disbursal date is invalid.";
            rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(),
                    entry.getArgs().get(0));
        }
    }

    if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) {
        errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid",
                "Please specify source of funds.");
    }

    if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) {
        errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid",
                "Please specify required external id.");
    }

    if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) {
        errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid",
                "Please specify loan purpose.");
    }

    validateAdministrativeAndAdditionalFees(errors);

    if (this.repaymentScheduleIndependentOfCustomerMeeting) {
        if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) {
            errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid",
                    "Please specify a valid recurring frequency for repayment day.");
        }
        if (this.weekly) {
            if (isInvalidDayOfWeekSelection()) {
                errors.rejectValue("repaymentDayOfWeek",
                        "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid",
                        "Please select a day of the week for repayment day.");
            }
        } else if (this.monthly) {
            if (this.monthlyDayOfMonthOptionSelected) {
                if (isInvalidDayOfMonthEntered()) {
                    errors.rejectValue("repaymentDayOfMonth",
                            "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid",
                            "Please select a day of the month for repayment day.");
                }
            } else if (this.monthlyWeekOfMonthOptionSelected) {
                if (isInvalidWeekOfMonthSelection()) {
                    errors.rejectValue("repaymentWeekOfMonth",
                            "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid",
                            "Please select a week of the month for repayment day.");
                }
                if (isInvalidDayOfWeekSelection()) {
                    errors.rejectValue("repaymentDayOfWeek",
                            "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid",
                            "Please select a day of the week for repayment day.");
                }
            }
        }

        if (this.variableInstallmentsAllowed) {
            if (this.selectedFeeId != null) {
                for (Number feeId : this.selectedFeeId) {
                    if (feeId != null) {
                        VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade
                                .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue());
                        if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) {
                            errors.rejectValue("selectedFeeId",
                                    "loanAccountFormBean.additionalfees.variableinstallments.invalid",
                                    new String[] { result.getFeeName() },
                                    "This type of fee cannot be applied to loan with variable installments.");
                        }
                    }
                }
            }

            int defaultFeeIndex = 0;
            if (this.defaultFeeId != null) {
                for (Number feeId : this.defaultFeeId) {
                    if (feeId != null) {
                        Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex];
                        if (feeSelectedForRemoval == null || !feeSelectedForRemoval) {
                            VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade
                                    .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue());
                            if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) {
                                errors.rejectValue("selectedFeeId",
                                        "loanAccountFormBean.defaultfees.variableinstallments.invalid",
                                        new String[] { result.getFeeName() },
                                        "This type of fee cannot be applied to loan with variable installments.");
                            }
                        }
                    }
                    defaultFeeIndex++;
                }
            }
        }
    }

    if (errors.hasErrors()) {
        for (FieldError fieldError : errors.getFieldErrors()) {
            MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField())
                    .codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage())
                    .args(fieldError.getArguments());

            messageContext.addMessage(builder.build());
        }
    }
}

From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java

private void validateAdministrativeAndAdditionalFees(Errors errors) {
    Set<Integer> feeSet = new HashSet<Integer>();
    if (this.selectedFeeId != null) {
        boolean noDuplicateExists = true;
        for (Number feeId : this.selectedFeeId) {
            if (feeId != null) {
                noDuplicateExists = feeSet.add(feeId.intValue());
                if (!noDuplicateExists) {
                    errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.invalid",
                            "Multiple instances of the same fee are not allowed.");
                    break;
                }// w  w  w  .  ja  v  a 2s .  c  o  m
            }
        }
    }

    int defaultFeeIndex = 0;
    if (this.defaultFeeId != null) {
        for (Number feeId : this.defaultFeeId) {
            if (feeId != null) {

                Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex];
                if (feeSelectedForRemoval == null || !feeSelectedForRemoval) {

                    Number amountOrRate = this.defaultFeeAmountOrRate[defaultFeeIndex];
                    if (amountOrRate == null) {
                        errors.rejectValue("defaultFeeId",
                                "loanAccountFormBean.defaultfees.amountOrRate.invalid",
                                "Please specify fee amount for administrative fee "
                                        + Integer.valueOf(defaultFeeIndex + 1).toString());
                    } else {
                        FeeDto selectedFee = findDefaultFee(feeId.intValue());
                        if (selectedFee.isRateBasedFee()) {
                            // maybe check based on 'interest rate' decimals?
                        } else {
                            BigDecimal feeAmountAsDecimal = new BigDecimal(amountOrRate.toString())
                                    .stripTrailingZeros();
                            int places = feeAmountAsDecimal.scale();
                            if (places > this.digitsAfterDecimalForMonetaryAmounts) {
                                errors.rejectValue("selectedFeeId",
                                        "loanAccountFormBean.defaultfees.amountOrRate.digits.after.decimal.invalid",
                                        new Object[] { Integer.valueOf(defaultFeeIndex + 1),
                                                this.digitsAfterDecimalForMonetaryAmounts },
                                        "Please specify fee amount for additional fee "
                                                + Integer.valueOf(defaultFeeIndex + 1).toString());
                            }

                            int digitsBefore = feeAmountAsDecimal.toBigInteger().toString().length();
                            if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) {
                                errors.rejectValue("selectedFeeId",
                                        "loanAccountFormBean.defaultfees.amountOrRate.digits.before.decimal.invalid",
                                        new Object[] { Integer.valueOf(defaultFeeIndex + 1),
                                                this.digitsAfterDecimalForMonetaryAmounts },
                                        "Please specify fee amount for additional fee "
                                                + Integer.valueOf(defaultFeeIndex + 1).toString());
                            }

                        }
                    }
                }
            }
            defaultFeeIndex++;
        }
    }

    int additionalFeeIndex = 0;
    if (this.selectedFeeId != null) {
        for (Number feeId : this.selectedFeeId) {
            if (feeId != null) {
                Number amountOrRate = this.selectedFeeAmount[additionalFeeIndex];
                if (amountOrRate == null) {
                    errors.rejectValue("selectedFeeId",
                            "loanAccountFormBean.additionalfees.amountOrRate.invalid",
                            "Please specify fee amount for additional fee "
                                    + Integer.valueOf(additionalFeeIndex + 1).toString());
                } else {
                    int digitsAllowedBefore, digitsAllowedAfter;
                    if (findAdditionalFee(feeId.intValue()).isRateBasedFee()) {
                        digitsAllowedBefore = this.digitsBeforeDecimalForInterest;
                        digitsAllowedAfter = this.digitsAfterDecimalForInterest;
                    } else {
                        digitsAllowedBefore = this.digitsBeforeDecimalForMonetaryAmounts;
                        digitsAllowedAfter = this.digitsAfterDecimalForMonetaryAmounts;
                    }

                    BigDecimal feeAmountAsDecimal = new BigDecimal(amountOrRate.toString())
                            .stripTrailingZeros();
                    int places = feeAmountAsDecimal.scale();
                    if (places > digitsAllowedAfter) {
                        errors.rejectValue("selectedFeeId",
                                "loanAccountFormBean.additionalfees.amountOrRate.digits.after.decimal.invalid",
                                new Object[] { Integer.valueOf(additionalFeeIndex + 1), digitsAllowedAfter },
                                "Please specify fee amount for additional fee "
                                        + Integer.valueOf(additionalFeeIndex + 1).toString());
                    }

                    int digitsBefore = feeAmountAsDecimal.toBigInteger().toString().length();
                    if (digitsBefore > digitsAllowedBefore) {
                        errors.rejectValue("selectedFeeId",
                                "loanAccountFormBean.additionalfees.amountOrRate.digits.before.decimal.invalid",
                                new Object[] { Integer.valueOf(additionalFeeIndex + 1), digitsAllowedBefore },
                                "Please specify fee amount for additional fee "
                                        + Integer.valueOf(additionalFeeIndex + 1).toString());
                    }
                }
            }
            additionalFeeIndex++;
        }
    }
}

From source file:uk.ac.ebi.fg.biostudies.utils.saxon.search.AbstractIndexEnvironment.java

public void indexFromXmlDB_FACETS(String indexLocationDirectory, String dbHost, int dbPort, String dbPassword,
        String dbName) throws Exception {
    int countNodes = 0;
    String driverXml = "";
    String connectionString = "";
    Collection coll;/*from   w ww .  j a  v  a 2  s. c  om*/
    IndexWriter w = null;
    Map<String, XPathExpression> fieldXpe = new HashMap<String, XPathExpression>();
    try {

        Directory indexTempDirectory = FSDirectory.open(new File(indexLocationDirectory, indexId));
        w = createIndex(indexTempDirectory, indexAnalyzer);

        Directory taxDir = FSDirectory.open(new File(indexLocationDirectory + "Facets", indexId));

        DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxDir);
        CategoryDocumentBuilder docBuilder = new CategoryDocumentBuilder(taxoWriter);

        HierarchicalConfiguration connsConf = (HierarchicalConfiguration) Application.getInstance()
                .getPreferences().getConfSubset("bs.xmldatabase");

        if (null != connsConf) {
            // TODO: rpe use the component XmlDatabasePooling
            driverXml = connsConf.getString("driver");
            // I will use the connectionString that was passed by parameter
            // (in several parameters)
            connectionString = connsConf.getString("base") + "://" + dbHost + ":" + dbPort + "/" + dbName;
        } else {
            logger.error("bs.xmldatabase Configuration is missing!!");
        }

        // I cannot register this database again (this is already registered
        // on XmlDbConnectionPool Component -
        // java.nio.channels.OverlappingFileLockException
        // c = Class.forName(driverXml);
        // db = (Database) c.newInstance();
        // DatabaseManager.registerDatabase(db);
        logger.debug("connectionString->" + connectionString);
        coll = DatabaseManager.getCollection(connectionString);
        XPathQueryService service = (XPathQueryService) coll.getService("XPathQueryService", "1.0");

        DocumentInfo source = null;
        // Loop through all result items

        // collect all the fields data
        Configuration config = ((SaxonEngine) Application.getAppComponent("SaxonEngine")).trFactory
                .getConfiguration();

        XPath xp = new XPathEvaluator(config);
        // XPathExpression xpe = xp.compile(this.env.indexDocumentPath);

        for (FieldInfo field : fields.values()) {
            fieldXpe.put(field.name, xp.compile(field.path));
            logger.debug("Field Path->[{}]", field.path);
        }

        // the xmldatabase is not very correct and have memory problem for
        // queires with huge results, so its necessary to implement our own
        // iteration mechanism
        //
        // // I will collect all the results
        // ResourceSet set = service.query(this.env.indexDocumentPath);
        // //TODO rpe
        // //ResourceSet set = service.query("//Sample");
        // logger.debug("Number of results->" + set.getSize());
        // long numberResults = set.getSize();
        long numberResults = 0;
        ResourceSet set = service.query("count(" + indexDocumentPath + ")");
        if (set.getIterator().hasMoreResources()) {
            numberResults = Integer.parseInt((String) set.getIterator().nextResource().getContent());
        }
        logger.debug("Number of results->" + numberResults);
        long pageSizeDefault = 50000;
        // the samplegroup cannot be big otherwise I will obtain a memory
        // error ... but the sample must b at least one million because the
        // paging queries are really slow - we need to balance it
        // (for samples 1million, for samplegroup 50000)
        if (numberResults > 1000000) {
            pageSizeDefault = 1000000;
        }

        long pageNumber = 1;
        int count = 0;
        Map<String, AttsInfo[]> cacheAtt = new HashMap<String, AttsInfo[]>();
        Map<String, XPathExpression> cacheXpathAtt = new HashMap<String, XPathExpression>();
        Map<String, XPathExpression> cacheXpathAttValue = new HashMap<String, XPathExpression>();
        while ((pageNumber * pageSizeDefault) <= (numberResults + pageSizeDefault - 1)) {
            // while ((pageNumber<=1)) {
            // calculate the last hit
            long pageInit = (pageNumber - 1) * pageSizeDefault + 1;
            long pageSize = (pageNumber * pageSizeDefault < numberResults) ? pageSizeDefault
                    : (numberResults - pageInit + 1);

            service = (XPathQueryService) coll.getService("XPathQueryService", "1.0");

            // xquery paging using subsequence function
            long time = System.nanoTime();

            // /set =
            // service.query("for $x in(/Biosamples/SampleGroup/Sample/@id) return string($x)");
            set = service.query("for $x in(subsequence(" + indexDocumentPath + "/@id," + pageInit + ","
                    + pageSize + ")) return string($x)");
            // logger.debug("Number of results of page->" + set.getSize());
            double ms = (System.nanoTime() - time) / 1000000d;
            logger.info("Query XMLDB took ->[{}]", ms);

            ResourceIterator iter = set.getIterator();
            XPath xp2;
            XPathExpression xpe2;
            List documentNodes;
            StringReader reader;
            // cache of distinct attributes fora each sample group

            while (iter.hasMoreResources()) {
                count++;
                logger.debug("its beeing processed the number ->" + count);
                String idSample = (String) iter.nextResource().getContent();
                logger.debug("idSample->" + idSample);
                // I need to get the sample
                ResourceSet setid = service.query(indexDocumentPath + "[@id='" + idSample + "']");

                // System.out.println("/Biosamples/SampleGroup/Sample[@id='"
                // + idSample + "']");
                ResourceIterator iterid = setid.getIterator();
                List<CategoryPath> sampleCategories = null;
                while (iterid.hasMoreResources()) {
                    // System.out.println("");
                    // /xml=(String) iterid.nextResource().getContent();

                    // /xml=(String) iter.nextResource().getContent();
                    // logger.debug("xml->"+xml);
                    // /reader = new StringReader(xml);
                    StringBuilder xml = new StringBuilder();
                    xml.append((String) iterid.nextResource().getContent());

                    // logger.debug(xml.toString());
                    reader = new StringReader(xml.toString());
                    source = config.buildDocument(new StreamSource(reader));

                    // logger.debug("XML DB->[{}]",
                    // PrintUtils.printNodeInfo((NodeInfo) source, config));
                    Document d = new Document();

                    xp2 = new XPathEvaluator(source.getConfiguration());

                    int position = indexDocumentPath.lastIndexOf("/");
                    ;
                    String pathRoot = "";
                    if (position != -1) {
                        pathRoot = indexDocumentPath.substring(position);
                    } else {
                        pathRoot = indexDocumentPath;
                    }
                    // logger.debug("PathRoot->[{}]",pathRoot);
                    xpe2 = xp2.compile(pathRoot);
                    // TODO rpe
                    // xpe2 = xp2.compile("/Sample");
                    documentNodes = (List) xpe2.evaluate(source, XPathConstants.NODESET);

                    for (Object node : documentNodes) {
                        // logger.debug("XML DB->[{}]",PrintUtils.printNodeInfo((NodeInfo)node,config));
                        for (FieldInfo field : fields.values()) {
                            try {

                                // Configuration
                                // config=doc.getConfiguration();
                                // I Just have to calculate the Xpath
                                if (!field.process) {

                                    List values = (List) fieldXpe.get(field.name).evaluate(node,
                                            XPathConstants.NODESET);
                                    // logger.debug("Field->[{}] values-> [{}]",
                                    // field.name,
                                    // values.toString());
                                    for (Object v : values) {

                                        if ("integer".equals(field.type)) {
                                            addIntIndexField(d, field.name, v, field.shouldStore,
                                                    field.shouldSort);

                                            // Just to test I will put here
                                            // one facet for the samples
                                            if (field.name.equalsIgnoreCase("samples")) {
                                                System.out.println("Value-->"
                                                        + v.toString());
                                                sampleCategories = new ArrayList<CategoryPath>();
                                                sampleCategories.add(new CategoryPath("samples", v.toString()));
                                            }

                                        } else if ("date".equals(field.type)) {
                                            // todo: addDateIndexField(d,
                                            // field.name,
                                            // v);
                                            logger.error(
                                                    "Date fields are not supported yet, field [{}] will not be created",
                                                    field.name);
                                        } else if ("boolean".equals(field.type)) {
                                            addBooleanIndexField(d, field.name, v, field.shouldSort);
                                        } else {
                                            addIndexField(d, field.name, v, field.shouldAnalyze,
                                                    field.shouldStore, field.shouldSort);
                                        }
                                    }

                                } else {
                                    if (field.name.equalsIgnoreCase("attributes")) {
                                        // implement here the biosamples
                                        // database sample attributes logic
                                        // TODO: rpe
                                        // logger.debug("There is A special treatment for this field->"
                                        // + field.name);

                                        List values = (List) fieldXpe.get(field.name).evaluate(node,
                                                XPathConstants.NODESET);

                                        // XPathExpression
                                        // classAtt=xp.compile("@class");
                                        // XPathExpression
                                        // typeAtt=xp.compile("@dataType");
                                        // XPathExpression
                                        // valueAtt=xp.compile("value");
                                        String groupId = (String) fieldXpe.get("samplegroup").evaluate(node,
                                                XPathConstants.STRING);
                                        String id = (String) fieldXpe.get("accession").evaluate(node,
                                                XPathConstants.STRING);

                                        // logger.debug(groupId+"$$$" + id);

                                        // logger.debug("Field->[{}] values-> [{}]",
                                        // field.name,
                                        // values.toString());

                                        AttsInfo[] attsInfo = null;
                                        if (cacheAtt.containsKey(groupId)) {
                                            attsInfo = cacheAtt.get(groupId);
                                        } else {
                                            logger.debug("No exists cache for samplegroup->" + groupId);
                                            // ResourceSet setAtt =
                                            // service.query("distinct-values(/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/Sample/attribute[@dataType!='INTEGER']/replace(@class,' ', '-'))");
                                            // /ResourceSet setAtt =
                                            // service.query("distinct-values(/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/Sample/attribute/replace(@class,' ', '-'))");
                                            // /ResourceSet setAtt =
                                            // service.query("distinct-values(/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/Sample/attribute/@class)");
                                            ResourceSet setAtt = service
                                                    .query("data(/Biosamples/SampleGroup[@id='" + groupId
                                                            + "']/SampleAttributes/attribute/@class)");
                                            // logger.debug("->"
                                            // +
                                            // "/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/SampleAttributes/attribute/@class");

                                            ResourceIterator resAtt = setAtt.getIterator();
                                            int i = 0;
                                            attsInfo = new AttsInfo[(int) setAtt.getSize()];
                                            while (resAtt.hasMoreResources()) {
                                                String classValue = (String) resAtt.nextResource().getContent();
                                                // logger.debug("->"
                                                // + classValue);
                                                // need to use this because
                                                // of the use of quotes in
                                                // the name of the classes
                                                String classValueWitoutQuotes = classValue.replaceAll("\"",
                                                        "\"\"");
                                                // logger.debug("Class value->"
                                                // + classValue);
                                                XPathExpression xpathAtt = null;
                                                XPathExpression xpathAttValue = null;
                                                if (cacheXpathAtt.containsKey(classValue)) {
                                                    xpathAtt = cacheXpathAtt.get(classValue);
                                                    xpathAttValue = cacheXpathAttValue.get(classValue);
                                                } else {

                                                    xpathAtt = xp.compile("./attribute[@class=\""
                                                            + classValueWitoutQuotes + "\"]/@dataType");

                                                    xpathAttValue = xp.compile(
                                                            "attribute[@class=\"" + classValueWitoutQuotes
                                                                    + "\"]/value/text()[last()]");

                                                    // logger.debug("attribute[@class=\""
                                                    // +
                                                    // classValueWitoutQuotes
                                                    // +
                                                    // "\"]//value/text()");
                                                    // //xpathAttValue=xp.compile("./attribute[@class=\""
                                                    // +
                                                    // classValueWitoutQuotes
                                                    // +
                                                    // "\"]/value[1]/text()");
                                                    // logger.debug("./attribute[@class=\""
                                                    // +
                                                    // classValueWitoutQuotes
                                                    // +
                                                    // "\"]/value[1]/text()");
                                                    cacheXpathAtt.put(classValue, xpathAtt);
                                                    cacheXpathAttValue.put(classValue, xpathAttValue);
                                                }
                                                // this doesnt work when the
                                                // first sample of sample
                                                // group doens have all the
                                                // attributes
                                                // im using \" becuse there
                                                // are some attributes thas
                                                // has ' on the name!!!
                                                // /ResourceSet setAttType =
                                                // service.query("string((/Biosamples/SampleGroup[@id='"
                                                // + groupId
                                                // +"']/Sample/attribute[@class=replace(\""
                                                // + classValueWitoutQuotes
                                                // +
                                                // "\",'-',' ')]/@dataType)[1])");
                                                // /ResourceSet setAttType =
                                                // service.query("string(/Biosamples/SampleGroup[@id='"
                                                // + groupId
                                                // +"']/Sample/attribute[@class=\""
                                                // + classValueWitoutQuotes
                                                // + "\"]/@dataType)");
                                                ResourceSet setAttType = service
                                                        .query("data(/Biosamples/SampleGroup[@id='" + groupId
                                                                + "']/SampleAttributes/attribute[@class=\""
                                                                + classValueWitoutQuotes + "\"]/@dataType)");
                                                String dataValue = (String) setAttType.getIterator()
                                                        .nextResource().getContent();
                                                // logger.debug("Data Type of "
                                                // + classValue + " ->" +
                                                // dataValue);
                                                // String
                                                // dataValue=(String)xpathAtt.evaluate(node,
                                                // XPathConstants.STRING);
                                                AttsInfo attsI = new AttsInfo(classValue, dataValue);
                                                // logger.debug("Atttribute->class"
                                                // + attsI.name + "->type->"
                                                // + attsI.type + "->i" +
                                                // i);
                                                attsInfo[i] = attsI;
                                                // logger.debug("distinct att->"
                                                // + value);
                                                // cacheAtt.put(groupId,
                                                // value);
                                                i++;
                                            }
                                            cacheAtt.put(groupId, attsInfo);
                                            // distinctAtt=cacheAtt.get(groupId);
                                            // logger.debug("Already exists->"
                                            // + distinctAtt);
                                        }
                                        int len = attsInfo.length;
                                        for (int i = 0; i < len; i++) {
                                            // logger.debug("$$$$$$->" +
                                            // attsInfo[i].name + "$$$$" +
                                            // attsInfo[i].type);
                                            if (!attsInfo[i].type.equalsIgnoreCase("integer")
                                                    && !attsInfo[i].type.equalsIgnoreCase("real")) {

                                                XPathExpression valPath = cacheXpathAttValue
                                                        .get(attsInfo[i].name);
                                                String val = (String) valPath.evaluate(node,
                                                        XPathConstants.STRING);
                                                // logger.debug("$$$$$$->" +
                                                // "STRING->" + val + "");
                                                addIndexField(d, (i + 1) + "", val, true, false, true);
                                            } else {
                                                XPathExpression valPath = cacheXpathAttValue
                                                        .get(attsInfo[i].name);
                                                String valS = (String) valPath.evaluate(node,
                                                        XPathConstants.STRING);
                                                valS = valS.trim();
                                                // logger.debug("Integer->"
                                                // + valS);
                                                int val = 0;
                                                if (valS == null || valS.equalsIgnoreCase("")
                                                        || valS.equalsIgnoreCase("NaN")) {
                                                    valS = "0";
                                                }
                                                // sort numbers as strings
                                                // logger.debug("class->" +
                                                // attsInfo[i].name
                                                // +"value->##"+ valS +
                                                // "##");
                                                BigDecimal num = new BigDecimal(valS);
                                                num = num.multiply(new BigDecimal(100));
                                                int taux = num.toBigInteger().intValue();
                                                valS = String.format("%07d", taux);
                                                // logger.debug("Integer->"
                                                // + valS + "position->"
                                                // +(i+1)+"integer");
                                                addIndexField(d, (i + 1) + "", valS, true, false, true);
                                                // addIntIndexField(d,
                                                // (i+1)+"integer", new
                                                // BigInteger(valS),false,
                                                // true);
                                                //
                                            }
                                        }

                                    } else {
                                        // logger.debug("There is NO special treatment for this field->"
                                        // + field.name);
                                    }
                                }
                            } catch (XPathExpressionException x) {
                                String xmlError = PrintUtils.printNodeInfo((NodeInfo) node, config);
                                logger.error("XML DB->[{}]", xmlError);
                                logger.error("Caught an exception while indexing expression [" + field.path
                                        + "] for document ["
                                        + ((NodeInfo) source).getStringValue().substring(0, 20) + "...]", x);
                                throw new Exception("Xml:" + xmlError, x);
                            }
                        }
                    }

                    documentNodes = null;
                    source = null;
                    reader = null;
                    xml = null;
                    countNodes++;
                    // logger.debug("count->[{}]", countNodes);

                    // facet tests

                    docBuilder.setCategoryPaths(sampleCategories);
                    docBuilder.build(d);

                    addIndexDocument(w, d);

                }
            }
            logger.debug("until now it were processed->[{}]", pageNumber * pageSizeDefault);
            pageNumber++;
            if (coll != null) {
                try {
                    // coll.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            set = null;

        }

        setCountDocuments(countNodes);
        // add metadata to the lucene index
        Map<String, String> map = new HashMap<String, String>();
        map.put("numberDocs", Integer.toString(countNodes));
        map.put("date", Long.toString(System.nanoTime()));
        // logger.debug(Application.getInstance().getComponent("XmlDbConnectionPool").getMetaDataInformation());
        // I cannot call directly
        // getComponent("XmlDbConnectionPool").getMetaDataInformation(),
        // because I can be working in a did
        String dbInfo = ((XmlDbConnectionPool) Application.getInstance().getComponent("XmlDbConnectionPool"))
                .getDBInfo(dbHost, dbPort, dbPassword, dbName);

        map.put("DBInfo", dbInfo);
        // facet
        taxoWriter.commit();
        taxoWriter.close();
        commitIndex(w, map);

    } catch (Exception x) {
        logger.error("Caught an exception:", x);
        w.close();
        throw x;
    }
}

From source file:uk.ac.ebi.arrayexpress.utils.saxon.search.AbstractIndexEnvironment.java

public void indexFromXmlDB_FACETS(String indexLocationDirectory, String dbHost, int dbPort, String dbPassword,
        String dbName) throws Exception {
    int countNodes = 0;
    String driverXml = "";
    String connectionString = "";
    Collection coll;/*from  ww w .ja v a  2 s .  com*/
    IndexWriter w = null;
    Map<String, XPathExpression> fieldXpe = new HashMap<String, XPathExpression>();
    try {

        Directory indexTempDirectory = FSDirectory.open(new File(indexLocationDirectory, indexId));
        w = createIndex(indexTempDirectory, indexAnalyzer);

        Directory taxDir = FSDirectory.open(new File(indexLocationDirectory + "Facets", indexId));

        DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxDir);
        CategoryDocumentBuilder docBuilder = new CategoryDocumentBuilder(taxoWriter);

        HierarchicalConfiguration connsConf = (HierarchicalConfiguration) Application.getInstance()
                .getPreferences().getConfSubset("bs.xmldatabase");

        if (null != connsConf) {
            // TODO: rpe use the component XmlDatabasePooling
            driverXml = connsConf.getString("driver");
            // I will use the connectionString that was passed by parameter
            // (in several parameters)
            connectionString = connsConf.getString("base") + "://" + dbHost + ":" + dbPort + "/" + dbName;
        } else {
            logger.error("bs.xmldatabase Configuration is missing!!");
        }

        // I cannot register this database again (this is already registered
        // on XmlDbConnectionPool Component -
        // java.nio.channels.OverlappingFileLockException
        // c = Class.forName(driverXml);
        // db = (Database) c.newInstance();
        // DatabaseManager.registerDatabase(db);
        logger.debug("connectionString->" + connectionString);
        coll = DatabaseManager.getCollection(connectionString);
        XPathQueryService service = (XPathQueryService) coll.getService("XPathQueryService", "1.0");

        DocumentInfo source = null;
        // Loop through all result items

        // collect all the fields data
        Configuration config = ((SaxonEngine) Application.getAppComponent("SaxonEngine")).trFactory
                .getConfiguration();

        XPath xp = new XPathEvaluator(config);
        // XPathExpression xpe = xp.compile(this.env.indexDocumentPath);

        for (FieldInfo field : fields.values()) {
            fieldXpe.put(field.name, xp.compile(field.path));
            logger.debug("Field Path->[{}]", field.path);
        }

        // the xmldatabase is not very correct and have memory problem for
        // queires with huge results, so its necessary to implement our own
        // iteration mechanism
        //
        // // I will collect all the results
        // ResourceSet set = service.query(this.env.indexDocumentPath);
        // //TODO rpe
        // //ResourceSet set = service.query("//Sample");
        // logger.debug("Number of results->" + set.getSize());
        // long numberResults = set.getSize();
        long numberResults = 0;
        ResourceSet set = service.query("count(" + indexDocumentPath + ")");
        if (set.getIterator().hasMoreResources()) {
            numberResults = Integer.parseInt((String) set.getIterator().nextResource().getContent());
        }
        logger.debug("Number of results->" + numberResults);
        long pageSizeDefault = 50000;
        // the samplegroup cannot be big otherwise I will obtain a memory
        // error ... but the sample must b at least one million because the
        // paging queries are really slow - we need to balance it
        // (for samples 1million, for samplegroup 50000)
        if (numberResults > 1000000) {
            pageSizeDefault = 1000000;
        }

        long pageNumber = 1;
        int count = 0;
        Map<String, AttsInfo[]> cacheAtt = new HashMap<String, AttsInfo[]>();
        Map<String, XPathExpression> cacheXpathAtt = new HashMap<String, XPathExpression>();
        Map<String, XPathExpression> cacheXpathAttValue = new HashMap<String, XPathExpression>();
        while ((pageNumber * pageSizeDefault) <= (numberResults + pageSizeDefault - 1)) {
            // while ((pageNumber<=1)) {
            // calculate the last hit
            long pageInit = (pageNumber - 1) * pageSizeDefault + 1;
            long pageSize = (pageNumber * pageSizeDefault < numberResults) ? pageSizeDefault
                    : (numberResults - pageInit + 1);

            service = (XPathQueryService) coll.getService("XPathQueryService", "1.0");

            // xquery paging using subsequence function
            long time = System.nanoTime();

            // /set =
            // service.query("for $x in(/Biosamples/SampleGroup/Sample/@id) return string($x)");
            set = service.query("for $x in(subsequence(" + indexDocumentPath + "/@id," + pageInit + ","
                    + pageSize + ")) return string($x)");
            // logger.debug("Number of results of page->" + set.getSize());
            double ms = (System.nanoTime() - time) / 1000000d;
            logger.info("Query XMLDB took ->[{}]", ms);

            ResourceIterator iter = set.getIterator();
            XPath xp2;
            XPathExpression xpe2;
            List documentNodes;
            StringReader reader;
            // cache of distinct attributes fora each sample group

            while (iter.hasMoreResources()) {
                count++;
                logger.debug("its beeing processed the number ->" + count);
                String idSample = (String) iter.nextResource().getContent();
                logger.debug("idSample->" + idSample);
                // I need to get the sample
                ResourceSet setid = service.query(indexDocumentPath + "[@id='" + idSample + "']");

                // System.out.println("/Biosamples/SampleGroup/Sample[@id='"
                // + idSample + "']");
                ResourceIterator iterid = setid.getIterator();
                List<CategoryPath> sampleCategories = null;
                while (iterid.hasMoreResources()) {
                    // System.out.println("");
                    // /xml=(String) iterid.nextResource().getContent();

                    // /xml=(String) iter.nextResource().getContent();
                    // logger.debug("xml->"+xml);
                    // /reader = new StringReader(xml);
                    StringBuilder xml = new StringBuilder();
                    xml.append((String) iterid.nextResource().getContent());

                    // logger.debug(xml.toString());
                    reader = new StringReader(xml.toString());
                    source = config.buildDocument(new StreamSource(reader));

                    // logger.debug("XML DB->[{}]",
                    // PrintUtils.printNodeInfo((NodeInfo) source, config));
                    Document d = new Document();

                    xp2 = new XPathEvaluator(source.getConfiguration());

                    int position = indexDocumentPath.lastIndexOf("/");
                    ;
                    String pathRoot = "";
                    if (position != -1) {
                        pathRoot = indexDocumentPath.substring(position);
                    } else {
                        pathRoot = indexDocumentPath;
                    }
                    // logger.debug("PathRoot->[{}]",pathRoot);
                    xpe2 = xp2.compile(pathRoot);
                    // TODO rpe
                    // xpe2 = xp2.compile("/Sample");
                    documentNodes = (List) xpe2.evaluate(source, XPathConstants.NODESET);

                    for (Object node : documentNodes) {
                        // logger.debug("XML DB->[{}]",PrintUtils.printNodeInfo((NodeInfo)node,config));
                        for (FieldInfo field : fields.values()) {
                            try {

                                // Configuration
                                // config=doc.getConfiguration();
                                // I Just have to calculate the Xpath
                                if (!field.process) {

                                    List values = (List) fieldXpe.get(field.name).evaluate(node,
                                            XPathConstants.NODESET);
                                    // logger.debug("Field->[{}] values-> [{}]",
                                    // field.name,
                                    // values.toString());
                                    for (Object v : values) {

                                        if ("integer".equals(field.type)) {
                                            addIntIndexField(d, field.name, v, field.shouldStore,
                                                    field.shouldSort);

                                            // Just to test I will put here
                                            // one facet for the samples
                                            if (field.name.equalsIgnoreCase("samples")) {
                                                System.out.println("Value-->" + v.toString());
                                                sampleCategories = new ArrayList<CategoryPath>();
                                                sampleCategories.add(new CategoryPath("samples", v.toString()));
                                            }

                                        } else if ("date".equals(field.type)) {
                                            // todo: addDateIndexField(d,
                                            // field.name,
                                            // v);
                                            logger.error(
                                                    "Date fields are not supported yet, field [{}] will not be created",
                                                    field.name);
                                        } else if ("boolean".equals(field.type)) {
                                            addBooleanIndexField(d, field.name, v, field.shouldSort);
                                        } else {
                                            addIndexField(d, field.name, v, field.shouldAnalyze,
                                                    field.shouldStore, field.shouldSort);
                                        }
                                    }

                                } else {
                                    if (field.name.equalsIgnoreCase("attributes")) {
                                        // implement here the biosamples
                                        // database sample attributes logic
                                        // TODO: rpe
                                        // logger.debug("There is A special treatment for this field->"
                                        // + field.name);

                                        List values = (List) fieldXpe.get(field.name).evaluate(node,
                                                XPathConstants.NODESET);

                                        // XPathExpression
                                        // classAtt=xp.compile("@class");
                                        // XPathExpression
                                        // typeAtt=xp.compile("@dataType");
                                        // XPathExpression
                                        // valueAtt=xp.compile("value");
                                        String groupId = (String) fieldXpe.get("samplegroup").evaluate(node,
                                                XPathConstants.STRING);
                                        String id = (String) fieldXpe.get("accession").evaluate(node,
                                                XPathConstants.STRING);

                                        // logger.debug(groupId+"$$$" + id);

                                        // logger.debug("Field->[{}] values-> [{}]",
                                        // field.name,
                                        // values.toString());

                                        AttsInfo[] attsInfo = null;
                                        if (cacheAtt.containsKey(groupId)) {
                                            attsInfo = cacheAtt.get(groupId);
                                        } else {
                                            logger.debug("No exists cache for samplegroup->" + groupId);
                                            // ResourceSet setAtt =
                                            // service.query("distinct-values(/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/Sample/attribute[@dataType!='INTEGER']/replace(@class,' ', '-'))");
                                            // /ResourceSet setAtt =
                                            // service.query("distinct-values(/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/Sample/attribute/replace(@class,' ', '-'))");
                                            // /ResourceSet setAtt =
                                            // service.query("distinct-values(/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/Sample/attribute/@class)");
                                            ResourceSet setAtt = service
                                                    .query("data(/Biosamples/SampleGroup[@id='" + groupId
                                                            + "']/SampleAttributes/attribute/@class)");
                                            // logger.debug("->"
                                            // +
                                            // "/Biosamples/SampleGroup[@id='"
                                            // + groupId +
                                            // "']/SampleAttributes/attribute/@class");

                                            ResourceIterator resAtt = setAtt.getIterator();
                                            int i = 0;
                                            attsInfo = new AttsInfo[(int) setAtt.getSize()];
                                            while (resAtt.hasMoreResources()) {
                                                String classValue = (String) resAtt.nextResource().getContent();
                                                // logger.debug("->"
                                                // + classValue);
                                                // need to use this because
                                                // of the use of quotes in
                                                // the name of the classes
                                                String classValueWitoutQuotes = classValue.replaceAll("\"",
                                                        "\"\"");
                                                // logger.debug("Class value->"
                                                // + classValue);
                                                XPathExpression xpathAtt = null;
                                                XPathExpression xpathAttValue = null;
                                                if (cacheXpathAtt.containsKey(classValue)) {
                                                    xpathAtt = cacheXpathAtt.get(classValue);
                                                    xpathAttValue = cacheXpathAttValue.get(classValue);
                                                } else {

                                                    xpathAtt = xp.compile("./attribute[@class=\""
                                                            + classValueWitoutQuotes + "\"]/@dataType");

                                                    xpathAttValue = xp.compile(
                                                            "attribute[@class=\"" + classValueWitoutQuotes
                                                                    + "\"]/value/text()[last()]");

                                                    // logger.debug("attribute[@class=\""
                                                    // +
                                                    // classValueWitoutQuotes
                                                    // +
                                                    // "\"]//value/text()");
                                                    // //xpathAttValue=xp.compile("./attribute[@class=\""
                                                    // +
                                                    // classValueWitoutQuotes
                                                    // +
                                                    // "\"]/value[1]/text()");
                                                    // logger.debug("./attribute[@class=\""
                                                    // +
                                                    // classValueWitoutQuotes
                                                    // +
                                                    // "\"]/value[1]/text()");
                                                    cacheXpathAtt.put(classValue, xpathAtt);
                                                    cacheXpathAttValue.put(classValue, xpathAttValue);
                                                }
                                                // this doesnt work when the
                                                // first sample of sample
                                                // group doens have all the
                                                // attributes
                                                // im using \" becuse there
                                                // are some attributes thas
                                                // has ' on the name!!!
                                                // /ResourceSet setAttType =
                                                // service.query("string((/Biosamples/SampleGroup[@id='"
                                                // + groupId
                                                // +"']/Sample/attribute[@class=replace(\""
                                                // + classValueWitoutQuotes
                                                // +
                                                // "\",'-',' ')]/@dataType)[1])");
                                                // /ResourceSet setAttType =
                                                // service.query("string(/Biosamples/SampleGroup[@id='"
                                                // + groupId
                                                // +"']/Sample/attribute[@class=\""
                                                // + classValueWitoutQuotes
                                                // + "\"]/@dataType)");
                                                ResourceSet setAttType = service
                                                        .query("data(/Biosamples/SampleGroup[@id='" + groupId
                                                                + "']/SampleAttributes/attribute[@class=\""
                                                                + classValueWitoutQuotes + "\"]/@dataType)");
                                                String dataValue = (String) setAttType.getIterator()
                                                        .nextResource().getContent();
                                                // logger.debug("Data Type of "
                                                // + classValue + " ->" +
                                                // dataValue);
                                                // String
                                                // dataValue=(String)xpathAtt.evaluate(node,
                                                // XPathConstants.STRING);
                                                AttsInfo attsI = new AttsInfo(classValue, dataValue);
                                                // logger.debug("Atttribute->class"
                                                // + attsI.name + "->type->"
                                                // + attsI.type + "->i" +
                                                // i);
                                                attsInfo[i] = attsI;
                                                // logger.debug("distinct att->"
                                                // + value);
                                                // cacheAtt.put(groupId,
                                                // value);
                                                i++;
                                            }
                                            cacheAtt.put(groupId, attsInfo);
                                            // distinctAtt=cacheAtt.get(groupId);
                                            // logger.debug("Already exists->"
                                            // + distinctAtt);
                                        }
                                        int len = attsInfo.length;
                                        for (int i = 0; i < len; i++) {
                                            // logger.debug("$$$$$$->" +
                                            // attsInfo[i].name + "$$$$" +
                                            // attsInfo[i].type);
                                            if (!attsInfo[i].type.equalsIgnoreCase("integer")
                                                    && !attsInfo[i].type.equalsIgnoreCase("real")) {

                                                XPathExpression valPath = cacheXpathAttValue
                                                        .get(attsInfo[i].name);
                                                String val = (String) valPath.evaluate(node,
                                                        XPathConstants.STRING);
                                                // logger.debug("$$$$$$->" +
                                                // "STRING->" + val + "");
                                                addIndexField(d, (i + 1) + "", val, true, false, true);
                                            } else {
                                                XPathExpression valPath = cacheXpathAttValue
                                                        .get(attsInfo[i].name);
                                                String valS = (String) valPath.evaluate(node,
                                                        XPathConstants.STRING);
                                                valS = valS.trim();
                                                // logger.debug("Integer->"
                                                // + valS);
                                                int val = 0;
                                                if (valS == null || valS.equalsIgnoreCase("")
                                                        || valS.equalsIgnoreCase("NaN")) {
                                                    valS = "0";
                                                }
                                                // sort numbers as strings
                                                // logger.debug("class->" +
                                                // attsInfo[i].name
                                                // +"value->##"+ valS +
                                                // "##");
                                                BigDecimal num = new BigDecimal(valS);
                                                num = num.multiply(new BigDecimal(100));
                                                int taux = num.toBigInteger().intValue();
                                                valS = String.format("%07d", taux);
                                                // logger.debug("Integer->"
                                                // + valS + "position->"
                                                // +(i+1)+"integer");
                                                addIndexField(d, (i + 1) + "", valS, true, false, true);
                                                // addIntIndexField(d,
                                                // (i+1)+"integer", new
                                                // BigInteger(valS),false,
                                                // true);
                                                //
                                            }
                                        }

                                    } else {
                                        // logger.debug("There is NO special treatment for this field->"
                                        // + field.name);
                                    }
                                }
                            } catch (XPathExpressionException x) {
                                String xmlError = PrintUtils.printNodeInfo((NodeInfo) node, config);
                                logger.error("XML DB->[{}]", xmlError);
                                logger.error("Caught an exception while indexing expression [" + field.path
                                        + "] for document ["
                                        + ((NodeInfo) source).getStringValue().substring(0, 20) + "...]", x);
                                throw new Exception("Xml:" + xmlError, x);
                            }
                        }
                    }

                    documentNodes = null;
                    source = null;
                    reader = null;
                    xml = null;
                    countNodes++;
                    // logger.debug("count->[{}]", countNodes);

                    // facet tests

                    docBuilder.setCategoryPaths(sampleCategories);
                    docBuilder.build(d);

                    addIndexDocument(w, d);

                }
            }
            logger.debug("until now it were processed->[{}]", pageNumber * pageSizeDefault);
            pageNumber++;
            if (coll != null) {
                try {
                    // coll.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            set = null;

        }

        setCountDocuments(countNodes);
        // add metadata to the lucene index
        Map<String, String> map = new HashMap<String, String>();
        map.put("numberDocs", Integer.toString(countNodes));
        map.put("date", Long.toString(System.nanoTime()));
        // logger.debug(Application.getInstance().getComponent("XmlDbConnectionPool").getMetaDataInformation());
        // I cannot call directly
        // getComponent("XmlDbConnectionPool").getMetaDataInformation(),
        // because I can be working in a did
        String dbInfo = ((XmlDbConnectionPool) Application.getInstance().getComponent("XmlDbConnectionPool"))
                .getDBInfo(dbHost, dbPort, dbPassword, dbName);

        map.put("DBInfo", dbInfo);
        // facet
        taxoWriter.commit();
        taxoWriter.close();
        commitIndex(w, map);

    } catch (Exception x) {
        logger.error("Caught an exception:", x);
        w.close();
        throw x;
    }
}