Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

To view the source code for java.math BigDecimal ONE.

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:pe.gob.mef.gescon.web.ui.RangoMB.java

public void save(ActionEvent event) {
    try {//w  w  w. j a  v a  2  s .  c  om
        if (CollectionUtils.isEmpty(this.getListaRango())) {
            this.setListaRango(Collections.EMPTY_LIST);
        }
        Rango rango = new Rango();
        rango.setVnombre(this.getNombre());
        rango.setVdescripcion(this.getDescripcion());
        if (!errorValidation(rango)) {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();
            RangoService service = (RangoService) ServiceFinder.findBean("RangoService");
            rango.setNrangoid(service.getNextPK());
            rango.setVnombre(StringUtils.upperCase(this.getNombre().trim()));
            rango.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim()));
            rango.setNactivo(BigDecimal.ONE);
            rango.setNtiponormaid(this.getSelectedTipoNorma());
            rango.setDfechacreacion(new Date());
            rango.setVusuariocreacion(user.getVlogin());
            service.saveOrUpdate(rango);
            this.setListaRango(service.getRangos());
            this.cleanAttributes();
            RequestContext.getCurrentInstance().execute("PF('newDialog').hide();");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.apache.phoenix.util.DateUtil.java

/**
 * Utility function to convert a {@link BigDecimal} value to {@link Timestamp}.
 *///from w w  w .j  av a 2  s.c  om
public static Timestamp getTimestamp(BigDecimal bd) {
    return DateUtil.getTimestamp(bd.longValue(),
            ((bd.remainder(BigDecimal.ONE).multiply(BigDecimal.valueOf(MILLIS_TO_NANOS_CONVERTOR)))
                    .intValue()));
}

From source file:pe.gob.mef.gescon.web.ui.PerfilMB.java

public void save(ActionEvent event) {
    try {/*from  ww w  . j  a v  a 2s  . c om*/
        if (CollectionUtils.isEmpty(this.getListaPerfils())) {
            this.setListaPerfils(Collections.EMPTY_LIST);
        }
        Perfil perfil = new Perfil();
        perfil.setVnombre(this.getNombre());
        perfil.setVdescripcion(this.getDescripcion());
        if (!errorValidation(perfil)) {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();
            PerfilService service = (PerfilService) ServiceFinder.findBean("PerfilService");
            perfil.setNperfilid(service.getNextPK());
            perfil.setVnombre(StringUtils.upperCase(this.getNombre().trim()));
            perfil.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim()));
            perfil.setNactivo(BigDecimal.ONE);
            perfil.setDfechacreacion(new Date());
            perfil.setVusuariocreacion(user.getVlogin());
            service.saveOrUpdate(perfil);
            this.setListaPerfils(service.getPerfils());
            this.cleanAttributes();
            RequestContext.getCurrentInstance().execute("PF('newDialog').hide();");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.gst.portfolio.shareproducts.serialization.ShareProductDataSerializer.java

public ShareProduct validateAndCreate(JsonCommand jsonCommand) {
    if (StringUtils.isBlank(jsonCommand.json())) {
        throw new InvalidJsonException();
    }/*from w w w  .  j  a v  a 2s  . c om*/
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(),
            ShareProductApiConstants.supportedParametersForCreate);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("sharesproduct");
    JsonElement element = jsonCommand.parsedJson();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject());
    final String productName = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.name_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.name_paramname).value(productName).notBlank()
            .notExceedingLengthOf(200);
    final String shortName = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.shortname_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.shortname_paramname).value(shortName)
            .notBlank().notExceedingLengthOf(4);
    String description = null;
    if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.description_paramname, element)) {
        description = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.description_paramname,
                element);
    }

    String externalId = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.externalid_paramname,
            element);
    // baseDataValidator.reset().parameter(ShareProductApiConstants.externalid_paramname).value(externalId).notBlank();

    Long totalNumberOfShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.totalshares_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.totalshares_paramname)
            .value(totalNumberOfShares).notNull().longGreaterThanZero();
    final Long sharesIssued = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.totalsharesissued_paramname, element);
    if (sharesIssued != null && totalNumberOfShares != null && sharesIssued > totalNumberOfShares) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.totalsharesissued_paramname)
                .value(sharesIssued).failWithCodeNoParameterAddedToErrorCode(
                        "sharesIssued.cannot.be.greater.than.totalNumberOfShares");
    }
    final String currencyCode = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.currency_paramname, element);
    final Integer digitsAfterDecimal = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(ShareProductApiConstants.digitsafterdecimal_paramname, element);
    final Integer inMultiplesOf = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(ShareProductApiConstants.inmultiplesof_paramname, element);
    final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf);

    final BigDecimal unitPrice = this.fromApiJsonHelper
            .extractBigDecimalNamed(ShareProductApiConstants.unitprice_paramname, element, locale);
    baseDataValidator.reset().parameter(ShareProductApiConstants.unitprice_paramname).value(unitPrice).notNull()
            .positiveAmount();

    BigDecimal shareCapitalValue = BigDecimal.ONE;
    if (sharesIssued != null && unitPrice != null) {
        shareCapitalValue = BigDecimal.valueOf(sharesIssued).multiply(unitPrice);
    }

    Integer accountingRule = this.fromApiJsonHelper
            .extractIntegerNamed(ShareProductApiConstants.accountingRuleParamName, element, locale);
    baseDataValidator.reset().parameter(ShareProductApiConstants.accountingRuleParamName).value(accountingRule)
            .notNull().integerGreaterThanZero();
    AccountingRuleType accountingRuleType = null;
    if (accountingRule != null) {
        accountingRuleType = AccountingRuleType.fromInt(accountingRule);
    }

    Long minimumClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.minimumshares_paramname, element);
    Long nominalClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.nominaltshares_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname)
            .value(nominalClientShares).notNull().longGreaterThanZero();
    if (minimumClientShares != null && nominalClientShares != null
            && !minimumClientShares.equals(nominalClientShares)) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname)
                .value(nominalClientShares).longGreaterThanNumber(minimumClientShares);
    }
    Long maximumClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.maximumshares_paramname, element);
    if (maximumClientShares != null && nominalClientShares != null
            && !maximumClientShares.equals(nominalClientShares)) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.maximumshares_paramname)
                .value(maximumClientShares).longGreaterThanNumber(nominalClientShares);
    }

    Set<ShareProductMarketPrice> marketPriceSet = asembleShareMarketPrice(element);
    Set<Charge> charges = assembleListOfProductCharges(element, currencyCode);
    Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed(
            ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element);

    Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed(
            ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale);
    PeriodFrequencyType minimumActivePeriodType = extractPeriodType(
            ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, element);
    if (minimumActivePeriod != null) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname)
                .value(minimumActivePeriodType.getValue())
                .integerSameAsNumber(PeriodFrequencyType.DAYS.getValue());
    }

    Integer lockinPeriod = this.fromApiJsonHelper
            .extractIntegerNamed(ShareProductApiConstants.lockperiod_paramname, element, locale);
    PeriodFrequencyType lockPeriodType = extractPeriodType(
            ShareProductApiConstants.lockinperiodfrequencytype_paramname, element);

    AppUser createdBy = platformSecurityContext.authenticatedUser();
    AppUser modifiedBy = createdBy;
    DateTime createdDate = DateUtils.getLocalDateTimeOfTenant().toDateTime();
    DateTime modifiedOn = createdDate;
    ShareProduct product = new ShareProduct(productName, shortName, description, externalId, currency,
            totalNumberOfShares, sharesIssued, unitPrice, shareCapitalValue, minimumClientShares,
            nominalClientShares, maximumClientShares, marketPriceSet, charges, allowdividendsForInactiveClients,
            lockinPeriod, lockPeriodType, minimumActivePeriod, minimumActivePeriodType, createdBy, createdDate,
            modifiedBy, modifiedOn, accountingRuleType);

    for (ShareProductMarketPrice data : marketPriceSet) {
        data.setShareProduct(product);
    }
    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }
    return product;
}

From source file:org.voltdb.TestParameterSet.java

public void testNullInObjectArray() throws IOException {
    // This test passes nulls and VoltType nulls in Object[] arrays where the arrays contain
    // all supported datatypes (with the exception that we currently don't support Timestamp or varbinary in Object arrays).
    // Each Object[] type passes in "null" and the VoltType Null equivalent.  Note that Object[] containing Strings will
    // support null and VoltType nulls as array elements.  But any other Sigil type class (big decimal, timestamp, varbinary)
    // DO NOT support nulls or VoltType nulls in Object[] arrays.

    Object o_array[] = null;/*from ww w  .  ja  va2s .c  o  m*/
    ParameterSet p1 = null;
    Object first_param[] = null;
    boolean failed = false;

    // SHOULD FAIL: Object array of nulls
    o_array = new Object[] { null, null, null };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD SUCCEED: Empty Object array of null
    o_array = new Object[] {};
    p1 = ParameterSet.fromArrayNoCopy(new Object[] {});
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD SUCCEED: Object array of Strings - pass null
    o_array = new Object[] { "Null", null, "not null" };
    p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD SUCCEED: Object array of Strings - pass VoltType null
    o_array = new Object[] { "Null", VoltType.NULL_STRING_OR_VARBINARY, "not null" };
    p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD FAIL: Object array of BigDecimal - pass both null
    o_array = new Object[] { BigDecimal.ONE, null, BigDecimal.TEN };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD FAIL: Object array of BigDecimal - pass both VoltType null
    o_array = new Object[] { BigDecimal.ONE, VoltType.NULL_DECIMAL, BigDecimal.TEN };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD FAIL: Object array of Byte - pass null
    o_array = new Object[] { new Byte((byte) 3), null, new Byte((byte) 15) };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD SUCCEED: Object array of Byte - pass VoltType null
    o_array = new Object[] { new Byte((byte) 3), VoltType.NULL_TINYINT, new Byte((byte) 15) };
    p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD FAIL: Object array of Short - pass null
    o_array = new Object[] { new Short((short) 3), null, new Short((short) 15) };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD SUCCEED: Object array of Short - pass VoltType null
    o_array = new Object[] { new Short((short) 3), VoltType.NULL_SMALLINT, new Short((short) 15) };
    p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD FAIL: Object array of Integer - pass null
    o_array = new Object[] { new Integer(3), null, new Integer(15) };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD SUCCEED: Integer array, pass VoltType null
    o_array = new Object[] { new Integer(3), VoltType.NULL_SMALLINT, new Integer(15) };
    p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD FAIL: Object array of Long - pass null
    o_array = new Object[] { new Long(3), null };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD SUCCEED: Object array of Long - pass VoltType null
    o_array = new Object[] { VoltType.NULL_BIGINT, new Long(15) };
    p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD FAIL: Object array of Float - pass null
    o_array = new Object[] { null, new Double(3.1415) };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD SUCCEED: Object array of Float - pass VoltType null
    o_array = new Object[] { new Double(3.1415), VoltType.NULL_FLOAT };
    p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    first_param = p1.toArray();
    assertEquals(first_param.length, p1.toArray().length);

    // SHOULD FAIL: Object array of Decimal - pass null
    o_array = new Object[] { new Double(3.1415), null, new Double(3.1415) };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // Object array of Timestamp - pass both null and VoltType null
    // Currently not supported
    o_array = new Object[] { new org.voltdb.types.TimestampType(123432), null,
            new org.voltdb.types.TimestampType(1233) };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // SHOULD FAIL: not supported
    o_array = new Object[] { new org.voltdb.types.TimestampType(123432), VoltType.NULL_TIMESTAMP,
            new org.voltdb.types.TimestampType(1233) };
    failed = false;
    try {
        p1 = ParameterSet.fromArrayNoCopy(o_array, 1);
    } catch (Exception ex) {
        failed = true;
    }
    assert (failed);

    // Object array of varbinary (byte array) - pass both null and VoltType null

    // Currently not supported
}

From source file:pe.gob.mef.gescon.web.ui.MaestroMB.java

public void save(ActionEvent event) {
    try {/*from   w  ww . j  ava  2  s . c o m*/
        if (CollectionUtils.isEmpty(this.getListaMaestro())) {
            this.setListaMaestro(Collections.EMPTY_LIST);
        }
        Maestro maestro = new Maestro();
        maestro.setVnombre(this.getNombre().trim().toUpperCase());
        maestro.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim()));
        if (!errorValidation(maestro)) {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();
            MaestroService service = (MaestroService) ServiceFinder.findBean("MaestroService");
            maestro.setNmaestroid(service.getNextPK());
            maestro.setNactivo(BigDecimal.ONE);
            maestro.setVusuariocreacion(user.getVlogin());
            maestro.setDfechacreacion(new Date());
            service.saveOrUpdate(maestro);
            this.setListaMaestro(service.getMaestros());
            this.cleanAttributes();
            RequestContext.getCurrentInstance().execute("PF('newDialog').hide();");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.apache.fineract.portfolio.shareproducts.serialization.ShareProductDataSerializer.java

public ShareProduct validateAndCreate(JsonCommand jsonCommand) {
    if (StringUtils.isBlank(jsonCommand.json())) {
        throw new InvalidJsonException();
    }/*w w  w.  j  a va  2  s. co m*/
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, jsonCommand.json(),
            ShareProductApiConstants.supportedParametersForCreate);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("sharesproduct");
    JsonElement element = jsonCommand.parsedJson();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject());
    final String productName = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.name_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.name_paramname).value(productName).notBlank()
            .notExceedingLengthOf(200);
    final String shortName = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.shortname_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.shortname_paramname).value(shortName)
            .notBlank().notExceedingLengthOf(4);
    String description = null;
    if (this.fromApiJsonHelper.parameterExists(ShareProductApiConstants.description_paramname, element)) {
        description = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.description_paramname,
                element);
    }

    String externalId = this.fromApiJsonHelper.extractStringNamed(ShareProductApiConstants.externalid_paramname,
            element);
    // baseDataValidator.reset().parameter(ShareProductApiConstants.externalid_paramname).value(externalId).notBlank();

    Long totalNumberOfShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.totalshares_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.totalshares_paramname)
            .value(totalNumberOfShares).notNull().longGreaterThanZero();
    final Long sharesIssued = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.totalsharesissued_paramname, element);
    if (sharesIssued != null && totalNumberOfShares != null && sharesIssued > totalNumberOfShares) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.totalsharesissued_paramname)
                .value(sharesIssued).failWithCodeNoParameterAddedToErrorCode(
                        "sharesIssued.cannot.be.greater.than.totalNumberOfShares");
    }
    final String currencyCode = this.fromApiJsonHelper
            .extractStringNamed(ShareProductApiConstants.currency_paramname, element);
    final Integer digitsAfterDecimal = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(ShareProductApiConstants.digitsafterdecimal_paramname, element);
    final Integer inMultiplesOf = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(ShareProductApiConstants.inmultiplesof_paramname, element);
    final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf);

    final BigDecimal unitPrice = this.fromApiJsonHelper
            .extractBigDecimalNamed(ShareProductApiConstants.unitprice_paramname, element, locale);
    baseDataValidator.reset().parameter(ShareProductApiConstants.unitprice_paramname).value(unitPrice).notNull()
            .positiveAmount();

    BigDecimal shareCapitalValue = BigDecimal.ONE;
    if (sharesIssued != null && unitPrice != null) {
        shareCapitalValue = BigDecimal.valueOf(sharesIssued).multiply(unitPrice);
    }

    Integer accountingRule = this.fromApiJsonHelper
            .extractIntegerNamed(ShareProductApiConstants.accountingRuleParamName, element, locale);
    baseDataValidator.reset().parameter(ShareProductApiConstants.accountingRuleParamName).value(accountingRule)
            .notNull().integerGreaterThanZero();
    AccountingRuleType accountingRuleType = null;
    if (accountingRule != null) {
        accountingRuleType = AccountingRuleType.fromInt(accountingRule);
    }

    Long minimumClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.minimumshares_paramname, element);
    Long nominalClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.nominaltshares_paramname, element);
    baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname)
            .value(nominalClientShares).notNull().longGreaterThanZero();
    if (minimumClientShares != null && nominalClientShares != null
            && !minimumClientShares.equals(nominalClientShares)) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.nominaltshares_paramname)
                .value(nominalClientShares).longGreaterThanNumber(minimumClientShares);
    }
    Long maximumClientShares = this.fromApiJsonHelper
            .extractLongNamed(ShareProductApiConstants.maximumshares_paramname, element);
    if (maximumClientShares != null && nominalClientShares != null
            && !maximumClientShares.equals(nominalClientShares)) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.maximumshares_paramname)
                .value(maximumClientShares).longGreaterThanNumber(nominalClientShares);
    }

    Set<ShareProductMarketPrice> marketPriceSet = asembleShareMarketPrice(element);
    Set<Charge> charges = assembleListOfProductCharges(element, currencyCode);
    Boolean allowdividendsForInactiveClients = this.fromApiJsonHelper.extractBooleanNamed(
            ShareProductApiConstants.allowdividendcalculationforinactiveclients_paramname, element);

    Integer minimumActivePeriod = this.fromApiJsonHelper.extractIntegerNamed(
            ShareProductApiConstants.minimumactiveperiodfordividends_paramname, element, locale);
    PeriodFrequencyType minimumActivePeriodType = extractPeriodType(
            ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname, element);
    if (minimumActivePeriod != null) {
        baseDataValidator.reset().parameter(ShareProductApiConstants.minimumactiveperiodfrequencytype_paramname)
                .value(minimumActivePeriodType.getValue())
                .integerSameAsNumber(PeriodFrequencyType.DAYS.getValue());
    }

    Integer lockinPeriod = this.fromApiJsonHelper
            .extractIntegerNamed(ShareProductApiConstants.lockperiod_paramname, element, locale);
    PeriodFrequencyType lockPeriodType = extractPeriodType(
            ShareProductApiConstants.lockinperiodfrequencytype_paramname, element);

    AppUser createdBy = platformSecurityContext.authenticatedUser();
    AppUser modifiedBy = createdBy;
    DateTime createdDate = DateUtils.getLocalDateTimeOfTenant().toDateTime();
    DateTime modifiedOn = createdDate;
    ShareProduct product = new ShareProduct(productName, shortName, description, externalId, currency,
            totalNumberOfShares, sharesIssued, unitPrice, shareCapitalValue, minimumClientShares,
            nominalClientShares, maximumClientShares, marketPriceSet, charges, allowdividendsForInactiveClients,
            lockinPeriod, lockPeriodType, minimumActivePeriod, minimumActivePeriodType, createdBy, createdDate,
            modifiedBy, modifiedOn, accountingRuleType);
    for (ShareProductMarketPrice data : marketPriceSet) {
        data.setShareProduct(product);
    }
    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }
    return product;
}

From source file:org.finra.herd.service.helper.BusinessObjectDefinitionHelper.java

/**
 * Processes the tags search score multiplier. Multiply all the tags search score.
 *
 * @param businessObjectDefinitionEntity the business object definition entity
 *///from www  .  ja va2  s  .com
public void processTagSearchScoreMultiplier(
        final BusinessObjectDefinitionEntity businessObjectDefinitionEntity) {
    LOGGER.debug("processTagSearchScoreMultiplier " + businessObjectDefinitionEntity.getId() + " "
            + businessObjectDefinitionEntity.getBusinessObjectDefinitionTags());
    BigDecimal totalSearchScoreMultiplier = businessObjectDefinitionEntity.getBusinessObjectDefinitionTags()
            .stream().filter(item -> item.getTag().getSearchScoreMultiplier() != null).reduce(BigDecimal.ONE,
                    (bd, item) -> bd.multiply(item.getTag().getSearchScoreMultiplier()), BigDecimal::multiply)
            .setScale(3, RoundingMode.HALF_UP);
    businessObjectDefinitionEntity.setTagSearchScoreMultiplier(totalSearchScoreMultiplier);
}

From source file:pe.gob.mef.gescon.web.ui.AlertaMB.java

public void cleanAttributes() {
    this.setId(BigDecimal.ZERO);
    this.setDescripcion(StringUtils.EMPTY);
    this.setNombre(StringUtils.EMPTY);
    this.setActivo(BigDecimal.ONE);
    this.setSelectedParametro(BigDecimal.ZERO);
    this.setCondicion1(BigDecimal.ONE);
    this.setCondicion2(BigDecimal.ONE);

    Iterator<FacesMessage> iter = FacesContext.getCurrentInstance().getMessages();
    if (iter.hasNext() == true) {
        iter.remove();//from  ww w.j a  va2  s.  co m
        FacesContext.getCurrentInstance().renderResponse();
    }
}

From source file:org.ScripterRon.TokenExchange.TokenAPI.java

/**
 * Process the API request/*  ww  w . j  a  va2  s.co m*/
 *
 * @param   req                 HTTP request
 * @return                      HTTP response
 * @throws  ParameterException  Parameter error detected
 */
@SuppressWarnings("unchecked")
@Override
protected JSONStreamAware processRequest(HttpServletRequest req) throws ParameterException {
    JSONObject response = new JSONObject();
    String function = Convert.emptyToNull(req.getParameter("function"));
    if (function == null) {
        return missing("function");
    }
    if (!BitcoinWallet.isWalletInitialized()) {
        return failure("Bitcoin wallet is not initialized yet");
    }
    BitcoinWallet.propagateContext();
    String heightString;
    String includeExchangedString;
    String accountString;
    String publicKeyString;
    String addressString;
    String amountString;
    String rateString;
    String txString;
    boolean includeExchanged;
    long accountId;
    int height;
    List<BitcoinAccount> accountList;
    BitcoinAccount account;
    switch (function) {
    case "getStatus":
        response.put("applicationName", TokenAddon.applicationName);
        response.put("applicationVersion", TokenAddon.applicationVersion);
        response.put("exchangeRate", TokenAddon.exchangeRate.toPlainString());
        response.put("currencyCode", TokenAddon.currencyCode);
        response.put("currencyId", Long.toUnsignedString(TokenAddon.currencyId));
        response.put("tokenAccount", Long.toUnsignedString(TokenAddon.accountId));
        response.put("tokenAccountRS", Convert.rsAccount(TokenAddon.accountId));
        List<Peer> peers = BitcoinWallet.getConnectedPeers();
        JSONArray connectedPeers = new JSONArray();
        peers.forEach((peer) -> {
            JSONObject JSONpeer = new JSONObject();
            PeerAddress peerAddress = peer.getAddress();
            VersionMessage versionMessage = peer.getPeerVersionMessage();
            JSONpeer.put("address", TokenAddon.formatAddress(peerAddress.getAddr(), peerAddress.getPort()));
            JSONpeer.put("version", versionMessage.clientVersion);
            JSONpeer.put("subVersion", versionMessage.subVer);
            connectedPeers.add(JSONpeer);
        });
        response.put("connectedPeers", connectedPeers);
        String downloadPeer = BitcoinWallet.getDownloadPeer();
        if (downloadPeer != null) {
            response.put("downloadPeer", downloadPeer);
        }
        response.put("nxtConfirmations", TokenAddon.nxtConfirmations);
        response.put("bitcoinConfirmations", TokenAddon.bitcoinConfirmations);
        response.put("walletAddress", BitcoinWallet.getWalletAddress());
        response.put("walletBalance", BitcoinWallet.getBalance().toPlainString());
        response.put("bitcoinTxFee", TokenAddon.bitcoinTxFee.toPlainString());
        response.put("bitcoinChainHeight", BitcoinWallet.getChainHeight());
        response.put("nxtChainHeight", Nxt.getBlockchain().getHeight());
        response.put("suspended", TokenAddon.isSuspended());
        if (TokenAddon.isSuspended()) {
            response.put("suspendReason", TokenAddon.getSuspendReason());
        }
        break;
    case "setExchangeRate":
        rateString = Convert.emptyToNull(req.getParameter("rate"));
        if (rateString == null) {
            return missing("rate");
        }
        try {
            BigDecimal rate = new BigDecimal(rateString).movePointRight(8).divideToIntegralValue(BigDecimal.ONE)
                    .movePointLeft(8).stripTrailingZeros();
            TokenDb.setExchangeRate(rate);
            response.put("processed", true);
        } catch (NumberFormatException exc) {
            return incorrect("rate", exc.getMessage());
        } catch (Exception exc) {
            Logger.logErrorMessage("SetExchangeRate failed", exc);
            return failure("Unable to set exchange rate: " + exc.getMessage());
        }
        break;
    case "getNxtTransactions":
        heightString = Convert.emptyToNull(req.getParameter("height"));
        if (heightString == null) {
            height = 0;
        } else {
            try {
                height = Integer.valueOf(heightString);
            } catch (NumberFormatException exc) {
                return incorrect("height", exc.getMessage());
            }
        }
        includeExchangedString = Convert.emptyToNull(req.getParameter("includeExchanged"));
        if (includeExchangedString == null) {
            includeExchanged = false;
        } else {
            includeExchanged = Boolean.valueOf(includeExchangedString);
        }
        try {
            List<TokenTransaction> tokenList = TokenDb.getTokens(height, includeExchanged);
            JSONArray tokenArray = new JSONArray();
            tokenList.forEach((token) -> {
                JSONObject tokenObject = new JSONObject();
                tokenObject.put("nxtTxId", Long.toUnsignedString(token.getNxtTxId()));
                tokenObject.put("sender", Long.toUnsignedString(token.getSenderId()));
                tokenObject.put("senderRS", token.getSenderIdRS());
                tokenObject.put("nxtChainHeight", token.getHeight());
                tokenObject.put("timestamp", token.getTimestamp());
                tokenObject.put("exchanged", token.isExchanged());
                tokenObject.put("tokenAmount", BigDecimal
                        .valueOf(token.getTokenAmount(), TokenAddon.currencyDecimals).toPlainString());
                tokenObject.put("bitcoinAmount",
                        BigDecimal.valueOf(token.getBitcoinAmount(), 8).toPlainString());
                tokenObject.put("address", token.getBitcoinAddress());
                if (token.getBitcoinTxId() != null) {
                    tokenObject.put("bitcoinTxId", token.getBitcoinTxIdString());
                }
                tokenArray.add(tokenObject);
            });
            response.put("transactions", tokenArray);
        } catch (Exception exc) {
            Logger.logErrorMessage("GetNxtTransactions failed", exc);
            return failure("Unable to get Nxt transactions: " + exc.getMessage());
        }
        break;
    case "suspend":
        TokenAddon.suspend("Suspended by the TokenExchange administrator");
        response.put("suspended", TokenAddon.isSuspended());
        break;
    case "resume":
        TokenAddon.resume();
        response.put("suspended", TokenAddon.isSuspended());
        break;
    case "getAddress":
        accountString = Convert.emptyToNull(req.getParameter("account"));
        if (accountString == null) {
            return missing("account");
        }
        try {
            accountId = Convert.parseAccountId(accountString);
        } catch (Exception exc) {
            return incorrect("account", exc.getMessage());
        }
        publicKeyString = Convert.emptyToNull(req.getParameter("publicKey"));
        byte[] publicKey;
        if (publicKeyString != null) {
            try {
                publicKey = Convert.parseHexString(publicKeyString);
            } catch (Exception exc) {
                return incorrect("publicKey", exc.getMessage());
            }
            if (publicKey.length != 32) {
                return incorrect("publicKey", "public key is not 32 bytes");
            }
            byte[] accountPublicKey = Account.getPublicKey(accountId);
            if (accountPublicKey != null && !Arrays.equals(accountPublicKey, publicKey)) {
                return incorrect("publicKey", "public key does not match account public key");
            }
        } else {
            publicKey = null;
        }
        try {
            accountList = TokenDb.getAccount(accountId);
            if (!accountList.isEmpty()) {
                account = accountList.get(accountList.size() - 1);
                if (TokenDb.transactionExists(account.getBitcoinAddress())) {
                    account = null;
                }
            } else {
                account = null;
            }
            if (account == null) {
                DeterministicKey key = BitcoinWallet.getNewKey();
                account = new BitcoinAccount(key, accountId, publicKey);
                TokenDb.storeAccount(account);
            }
            formatAccount(account, response);
        } catch (Exception exc) {
            Logger.logErrorMessage("GetAddress failed", exc);
            return failure("Unable to get new Bitcoin address: " + exc.getMessage());
        }
        break;
    case "getAccounts":
        JSONArray accountArray = new JSONArray();
        accountString = Convert.emptyToNull(req.getParameter("account"));
        addressString = Convert.emptyToNull(req.getParameter("address"));
        try {
            if (accountString != null) {
                try {
                    accountId = Convert.parseAccountId(accountString);
                } catch (Exception exc) {
                    return incorrect("account", exc.getMessage());
                }
                accountList = TokenDb.getAccount(accountId);
                accountList.forEach((a) -> accountArray.add(formatAccount(a, new JSONObject())));
            } else if (addressString != null) {
                account = TokenDb.getAccount(addressString);
                if (account != null) {
                    accountArray.add(formatAccount(account, new JSONObject()));
                }
            } else {
                accountList = TokenDb.getAccounts();
                accountList.forEach((a) -> accountArray.add(formatAccount(a, new JSONObject())));
            }
            response.put("accounts", accountArray);
        } catch (Exception exc) {
            Logger.logErrorMessage("GetAccounts failed", exc);
            return failure("Unable to get accounts: " + exc.getMessage());
        }
        break;
    case "deleteAddress":
        addressString = Convert.emptyToNull(req.getParameter("address"));
        if (addressString == null) {
            return missing("address");
        }
        try {
            boolean deleted = TokenDb.deleteAccountAddress(addressString);
            if (deleted) {
                BitcoinWallet.removeAddress(addressString);
            }
            response.put("deleted", deleted);
        } catch (Exception exc) {
            Logger.logErrorMessage("DeleteAddress failed", exc);
            return failure("Unable to delete account: " + exc.getMessage());
        }
        break;
    case "getBitcoinTransactions":
        JSONArray txArray = new JSONArray();
        addressString = Convert.emptyToNull(req.getParameter("address"));
        heightString = Convert.emptyToNull(req.getParameter("height"));
        if (heightString == null) {
            height = 0;
        } else {
            try {
                height = Integer.valueOf(heightString);
            } catch (NumberFormatException exc) {
                return incorrect("height", exc.getMessage());
            }
        }
        includeExchangedString = Convert.emptyToNull(req.getParameter("includeExchanged"));
        if (includeExchangedString == null) {
            includeExchanged = false;
        } else {
            includeExchanged = Boolean.valueOf(includeExchangedString);
        }
        try {
            List<BitcoinTransaction> txList = TokenDb.getTransactions(height, addressString, includeExchanged);
            txList.forEach((tx) -> {
                JSONObject txJSON = new JSONObject();
                txJSON.put("bitcoinTxId", tx.getBitcoinTxIdString());
                txJSON.put("bitcoinBlockId", tx.getBitcoinBlockIdString());
                txJSON.put("bitcoinChainHeight", tx.getHeight());
                txJSON.put("timestamp", tx.getTimestamp());
                txJSON.put("address", tx.getBitcoinAddress());
                txJSON.put("bitcoinAmount", BigDecimal.valueOf(tx.getBitcoinAmount(), 8).toPlainString());
                txJSON.put("tokenAmount",
                        BigDecimal.valueOf(tx.getTokenAmount(), TokenAddon.currencyDecimals).toPlainString());
                txJSON.put("account", Long.toUnsignedString(tx.getAccountId()));
                txJSON.put("accountRS", tx.getAccountIdRS());
                txJSON.put("exchanged", tx.isExchanged());
                if (tx.getNxtTxId() != 0) {
                    txJSON.put("nxtTxId", Long.toUnsignedString(tx.getNxtTxId()));
                }
                txArray.add(txJSON);
            });
            response.put("transactions", txArray);
        } catch (Exception exc) {
            Logger.logErrorMessage("GetBitcoinTransactions failed", exc);
            return failure("Unable to get Bitcoin transactions: " + exc.getMessage());
        }
        break;
    case "sendBitcoins":
        BitcoinWallet.propagateContext();
        addressString = Convert.emptyToNull(req.getParameter("address"));
        amountString = Convert.emptyToNull(req.getParameter("amount"));
        if (addressString == null) {
            return missing("address");
        }
        if (amountString == null) {
            return missing("amount");
        }
        try {
            Address toAddress = Address.fromBase58(BitcoinWallet.getNetworkParameters(), addressString);
            BigDecimal amount = new BigDecimal(amountString).movePointRight(8)
                    .divideToIntegralValue(BigDecimal.ONE).movePointLeft(8).stripTrailingZeros();
            txString = BitcoinWallet.sendCoins(toAddress, amount);
            response.put("transaction", txString);
        } catch (NumberFormatException exc) {
            return incorrect("amount", exc.getMessage());
        } catch (AddressFormatException exc) {
            return incorrect("address", exc.getMessage());
        } catch (Exception exc) {
            Logger.logErrorMessage("SendBitcoins failed", exc);
            return failure("Unable to send coins: " + exc.getMessage());
        }
        break;
    case "emptyWallet":
        BitcoinWallet.propagateContext();
        addressString = Convert.emptyToNull(req.getParameter("address"));
        if (addressString == null) {
            return missing("address");
        }
        try {
            Address toAddress = Address.fromBase58(BitcoinWallet.getNetworkParameters(), addressString);
            txString = BitcoinWallet.emptyWallet(toAddress);
            response.put("transaction", txString);
        } catch (AddressFormatException exc) {
            return incorrect("address", exc.getMessage());
        } catch (Exception exc) {
            Logger.logErrorMessage("EmptyWallet failed", exc);
            return failure("Unable to empty wallet: " + exc.getMessage());
        }
        break;
    case "rollbackChain":
        heightString = Convert.emptyToNull(req.getParameter("height"));
        if (heightString == null) {
            return missing("height");
        }
        try {
            height = Integer.valueOf(heightString);
            if (height < 0) {
                return incorrect("height", "The requested height is not valid");
            }
            boolean success = BitcoinWallet.rollbackChain(height);
            response.put("completed", success);
        } catch (NumberFormatException exc) {
            return incorrect("height", exc.getMessage());
        } catch (Exception exc) {
            Logger.logErrorMessage("RollbackChain failed", exc);
            return failure("Unable to rollback chain: " + exc.getMessage());
        }
        break;
    default:
        return unknown(function);
    }
    return response;
}