Example usage for java.math BigDecimal intValue

List of usage examples for java.math BigDecimal intValue

Introduction

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

Prototype

@Override
public int intValue() 

Source Link

Document

Converts this BigDecimal to an int .

Usage

From source file:easycare.load.util.db.loader.UserDataLoader.java

private void createUsersWithSubsetLocations(ContextOfCurrentLoad context, Organisation organisation,
        String organisationNumber) {
    List<Location> locations = organisation.activeLocations();
    BigDecimal totalLocations = BigDecimal.valueOf(locations.size());
    BigDecimal twoThirdLocations = totalLocations
            .divide(BigDecimal.valueOf(_THREE), _SIX, RoundingMode.HALF_EVEN).multiply(BigDecimal.valueOf(2))
            .setScale(0, RoundingMode.CEILING);
    Location[] locationsToAdd = locations.subList(0, twoThirdLocations.intValue()).toArray(new Location[0]);
    List<Role> roles = newArrayList(seedData.getRole(ROLE_CLINICIAN));
    buildUser(context, "remy" + organisationNumber, "Remy", "Roam", organisation, roles, organisationNumber,
            locationsToAdd);// w  w  w  .j av a2s  . c o m
}

From source file:org.yes.cart.service.domain.impl.PriceServiceImpl.java

/**
 * Nice rounding for digits.// ww w .  j  a v a 2  s.co m
 *
 * @param toNicefy digit to make it nice
 * @return nicefied digit
 */
BigDecimal niceBigDecimal(final BigDecimal toNicefy) {
    Integer intValue = toNicefy.intValue();
    String intAsString = intValue.toString();

    int tailZeroCount = intAsString.length() / 2;
    if (tailZeroCount == 0) {
        tailZeroCount = intAsString.length();

    }

    return new BigDecimal(intValue).setScale(-1 * tailZeroCount, BigDecimal.ROUND_HALF_UP);
}

From source file:com.gst.portfolio.collectionsheet.serialization.CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java

public CollectionSheetBulkRepaymentCommand commandFromApiJson(final String json,
        final PaymentDetail paymentDetail) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }/*from ww  w.  ja v a 2s. c  om*/

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element);

    final String note = this.fromApiJsonHelper.extractStringNamed("note", element);

    final JsonObject topLevelJsonElement = element.getAsJsonObject();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);

    SingleRepaymentCommand[] loanRepaymentTransactions = null;

    if (element.isJsonObject()) {
        if (topLevelJsonElement.has("bulkRepaymentTransactions")
                && topLevelJsonElement.get("bulkRepaymentTransactions").isJsonArray()) {
            final JsonArray array = topLevelJsonElement.get("bulkRepaymentTransactions").getAsJsonArray();
            loanRepaymentTransactions = new SingleRepaymentCommand[array.size()];
            for (int i = 0; i < array.size(); i++) {
                final JsonObject loanTransactionElement = array.get(i).getAsJsonObject();

                final Long loanId = this.fromApiJsonHelper.extractLongNamed("loanId", loanTransactionElement);
                final BigDecimal transactionAmount = this.fromApiJsonHelper
                        .extractBigDecimalNamed("transactionAmount", loanTransactionElement, locale);
                PaymentDetail detail = paymentDetail;
                if (paymentDetail == null) {
                    detail = this.paymentDetailAssembler.fetchPaymentDetail(loanTransactionElement);
                }
                if (transactionAmount != null && transactionAmount.intValue() > 0) {
                    loanRepaymentTransactions[i] = new SingleRepaymentCommand(loanId, transactionAmount,
                            transactionDate, detail);
                }
            }
        }
    }
    return new CollectionSheetBulkRepaymentCommand(note, transactionDate, loanRepaymentTransactions);
}

From source file:org.openhab.binding.homematic.handler.HomematicThingHandler.java

/**
 * {@inheritDoc}//w  w w. jav a 2  s .co m
 */
@Override
public void handleConfigurationUpdate(Map<String, Object> configurationParameters)
        throws ConfigValidationException {
    validateConfigurationParameters(configurationParameters);

    try {
        HomematicGateway gateway = getHomematicGateway();
        HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(getThing()));

        for (Entry<String, Object> configurationParmeter : configurationParameters.entrySet()) {
            String key = configurationParmeter.getKey();
            Object newValue = configurationParmeter.getValue();

            if (key.startsWith("HMP_")) {
                key = StringUtils.removeStart(key, "HMP_");
                Integer channelNumber = NumberUtils.toInt(StringUtils.substringBefore(key, "_"));
                String dpName = StringUtils.substringAfter(key, "_");

                HmDatapointInfo dpInfo = new HmDatapointInfo(device.getAddress(), HmParamsetType.MASTER,
                        channelNumber, dpName);
                HmDatapoint dp = device.getChannel(channelNumber).getDatapoint(dpInfo);

                if (dp != null) {
                    try {
                        if (newValue != null) {
                            if (newValue instanceof BigDecimal) {
                                final BigDecimal decimal = (BigDecimal) newValue;
                                if (dp.isIntegerType()) {
                                    newValue = decimal.intValue();
                                } else if (dp.isFloatType()) {
                                    newValue = decimal.doubleValue();
                                }
                            }
                            if (ObjectUtils.notEqual(dp.isEnumType() ? dp.getOptionValue() : dp.getValue(),
                                    newValue)) {
                                gateway.sendDatapoint(dp, new HmDatapointConfig(), newValue);
                            }
                        }
                    } catch (IOException ex) {
                        logger.error("Error setting thing property {}: {}", dpInfo, ex.getMessage());
                    }
                } else {
                    logger.error("Can't find datapoint for thing property {}", dpInfo);
                }
            }
        }
        gateway.triggerDeviceValuesReload(device);
    } catch (HomematicClientException | BridgeHandlerNotAvailableException ex) {
        logger.error("Error setting thing properties: {}", ex.getMessage(), ex);
    }
}

From source file:com.idega.block.oauth2.client.business.impl.GoogleLoginServiceImpl.java

private Object getUserToken(String clientId, String clientSecret) {
    // Authentication to the services is accomplished through HTTP requests
    // see https://developers.google.com/accounts/docs/OAuth2ForDevices
    // OAuth 2.0 for devices doesn't seem to be available in libraries yet.

    BasicNameValuePair[] params = { new BasicNameValuePair(PRM_CLIENT_ID, clientId),
            new BasicNameValuePair("scope", SCOPES.get(0) + CoreConstants.SPACE + SCOPES.get(1)) };

    UrlEncodedFormEntity urlEncodedFormEntity = null;
    try {//from   ww  w. j a  v  a2 s .c  o m
        urlEncodedFormEntity = new UrlEncodedFormEntity(Arrays.asList(params));
    } catch (UnsupportedEncodingException e1) {
        getLogger().log(Level.WARNING, "URL encoding is not supported, cause of: ", e1);
    }

    //urlEncodedFormEntity.setContentEncoding(HTTP.UTF_8);

    HttpResponse response = null;
    ApacheHttpTransport transport = new ApacheHttpTransport();
    org.apache.http.client.HttpClient httpclient = transport.getHttpClient();
    try {
        response = httpclient.execute(getAuthorizationRequest(urlEncodedFormEntity));
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    GenericJson userCodeValues = null;

    if (response != null) {
        try {
            JacksonFactory factory = new JacksonFactory();

            InputStream is = response.getEntity().getContent();
            JsonParser parser = factory.createJsonParser(is);
            userCodeValues = parser.parse(GenericJson.class, null);
            is.close();

            BigDecimal expires = (BigDecimal) userCodeValues.get("expires_in");
            Properties properties = new Properties();
            properties.put("expires_in", Integer.toString(expires.intValue()));
            BigDecimal interval = (BigDecimal) userCodeValues.get("interval");
            properties.put("interval", Integer.toString(interval.intValue()));
            properties.put("device_code", userCodeValues.get("device_code"));
            properties.put("verification_url", userCodeValues.get("verification_url"));
            properties.put("user_code", userCodeValues.get("user_code"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return null;
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.translator.ExprNodeConverter.java

/**
 * TODO: 1. Handle NULL//from  w  w w.j a  va 2s.  c o m
 */
@Override
public ExprNodeDesc visitLiteral(RexLiteral literal) {
    RelDataType lType = literal.getType();

    switch (literal.getType().getSqlTypeName()) {
    case BOOLEAN:
        return new ExprNodeConstantDesc(TypeInfoFactory.booleanTypeInfo,
                Boolean.valueOf(RexLiteral.booleanValue(literal)));
    case TINYINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.byteTypeInfo,
                Byte.valueOf(((Number) literal.getValue3()).byteValue()));
    case SMALLINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.shortTypeInfo,
                Short.valueOf(((Number) literal.getValue3()).shortValue()));
    case INTEGER:
        return new ExprNodeConstantDesc(TypeInfoFactory.intTypeInfo,
                Integer.valueOf(((Number) literal.getValue3()).intValue()));
    case BIGINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.longTypeInfo,
                Long.valueOf(((Number) literal.getValue3()).longValue()));
    case FLOAT:
    case REAL:
        return new ExprNodeConstantDesc(TypeInfoFactory.floatTypeInfo,
                Float.valueOf(((Number) literal.getValue3()).floatValue()));
    case DOUBLE:
        return new ExprNodeConstantDesc(TypeInfoFactory.doubleTypeInfo,
                Double.valueOf(((Number) literal.getValue3()).doubleValue()));
    case DATE:
        return new ExprNodeConstantDesc(TypeInfoFactory.dateTypeInfo,
                new Date(((Calendar) literal.getValue()).getTimeInMillis()));
    case TIME:
    case TIMESTAMP: {
        Object value = literal.getValue3();
        if (value instanceof Long) {
            value = new Timestamp((Long) value);
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.timestampTypeInfo, value);
    }
    case BINARY:
        return new ExprNodeConstantDesc(TypeInfoFactory.binaryTypeInfo, literal.getValue3());
    case DECIMAL:
        return new ExprNodeConstantDesc(
                TypeInfoFactory.getDecimalTypeInfo(lType.getPrecision(), lType.getScale()),
                literal.getValue3());
    case VARCHAR: {
        int varcharLength = lType.getPrecision();
        // If we cannot use Varchar due to type length restrictions, we use String
        if (varcharLength < 1 || varcharLength > HiveVarchar.MAX_VARCHAR_LENGTH) {
            return new ExprNodeConstantDesc(TypeInfoFactory.stringTypeInfo, literal.getValue3());
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.getVarcharTypeInfo(varcharLength),
                new HiveVarchar((String) literal.getValue3(), varcharLength));
    }
    case CHAR: {
        int charLength = lType.getPrecision();
        // If we cannot use Char due to type length restrictions, we use String
        if (charLength < 1 || charLength > HiveChar.MAX_CHAR_LENGTH) {
            return new ExprNodeConstantDesc(TypeInfoFactory.stringTypeInfo, literal.getValue3());
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.getCharTypeInfo(charLength),
                new HiveChar((String) literal.getValue3(), charLength));
    }
    case INTERVAL_YEAR_MONTH: {
        BigDecimal monthsBd = (BigDecimal) literal.getValue();
        return new ExprNodeConstantDesc(TypeInfoFactory.intervalYearMonthTypeInfo,
                new HiveIntervalYearMonth(monthsBd.intValue()));
    }
    case INTERVAL_DAY_TIME: {
        BigDecimal millisBd = (BigDecimal) literal.getValue();
        // Calcite literal is in millis, we need to convert to seconds
        BigDecimal secsBd = millisBd.divide(BigDecimal.valueOf(1000));
        return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
                new HiveIntervalDayTime(secsBd));
    }
    case OTHER:
    default:
        return new ExprNodeConstantDesc(TypeInfoFactory.voidTypeInfo, literal.getValue3());
    }
}

From source file:org.libreplan.business.workingday.IntraDayDate.java

private EffortDuration calculateProportionalDuration(ResourcesPerDay resourcesPerDay, EffortDuration effort) {
    int seconds = effort.getSeconds();
    BigDecimal end = new BigDecimal(seconds).divide(resourcesPerDay.getAmount(), RoundingMode.HALF_UP);
    return seconds(end.intValue());
}

From source file:com.griddynamics.jagger.engine.e1.scenario.DefaultWorkloadSuggestionMaker.java

@Override
public WorkloadConfiguration suggest(BigDecimal desiredTps, NodeTpsStatistics statistics, int maxThreads) {
    log.debug("Going to suggest workload configuration. desired tps {}. statistics {}", desiredTps, statistics);

    Table<Integer, Integer, Pair<Long, BigDecimal>> threadDelayStats = statistics.getThreadDelayStats();

    if (areEqual(desiredTps, BigDecimal.ZERO)) {
        return WorkloadConfiguration.with(0, 0);
    }/*  w w w.j a  v  a2s. c o m*/

    if (threadDelayStats.isEmpty()) {
        throw new IllegalArgumentException("Cannot suggest workload configuration");
    }

    if (!threadDelayStats.contains(CALIBRATION_CONFIGURATION.getThreads(),
            CALIBRATION_CONFIGURATION.getDelay())) {
        log.debug("Statistics is empty. Going to return calibration info.");
        return CALIBRATION_CONFIGURATION;
    }
    if (threadDelayStats.size() == 2 && areEqual(threadDelayStats.get(1, 0).getSecond(), BigDecimal.ZERO)) {
        log.warn("No calibration info. Going to retry.");
        return CALIBRATION_CONFIGURATION;
    }

    Map<Integer, Pair<Long, BigDecimal>> noDelays = threadDelayStats.column(0);

    log.debug("Calculate next thread count");
    Integer threadCount = findClosestPoint(desiredTps, noDelays);

    if (threadCount == 0) {
        threadCount = 1;
    }

    if (threadCount > maxThreads) {
        log.warn("{} calculated max {} allowed", threadCount, maxThreads);
        threadCount = maxThreads;
    }

    int currentThreads = statistics.getCurrentWorkloadConfiguration().getThreads();
    int diff = threadCount - currentThreads;
    if (diff > maxDiff) {
        log.debug("Increasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        return WorkloadConfiguration.with(currentThreads + maxDiff, 0);
    }

    diff = currentThreads - threadCount;
    if (diff > maxDiff) {
        log.debug("Decreasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        if ((currentThreads - maxDiff) > 1) {
            return WorkloadConfiguration.with(currentThreads - maxDiff, 0);
        } else {
            return WorkloadConfiguration.with(1, 0);
        }
    }

    if (!threadDelayStats.contains(threadCount, 0)) {
        return WorkloadConfiguration.with(threadCount, 0);
    }

    // <delay, <timestamp,tps>>
    Map<Integer, Pair<Long, BigDecimal>> delays = threadDelayStats.row(threadCount);

    // not enough statistics to calculate
    if (delays.size() == 1) {
        int delay = 0;
        BigDecimal tpsFromStat = delays.get(0).getSecond();

        // try to guess
        // tpsFromStat can be zero if no statistics was captured till this time
        if ((tpsFromStat.compareTo(BigDecimal.ZERO) > 0) && (desiredTps.compareTo(BigDecimal.ZERO) > 0)) {

            BigDecimal oneSecond = new BigDecimal(TimeUtils.secondsToMillis(1));
            BigDecimal result = oneSecond.multiply(new BigDecimal(threadCount)).divide(desiredTps, 3,
                    BigDecimal.ROUND_HALF_UP);
            result = result.subtract(oneSecond.multiply(new BigDecimal(threadCount)).divide(tpsFromStat, 3,
                    BigDecimal.ROUND_HALF_UP));

            delay = result.intValue();
        }
        // to have some non zero point in statistics
        if (delay == 0) {
            delay = MIN_DELAY;
        }

        delay = checkDelayInRange(delay);
        return WorkloadConfiguration.with(threadCount, delay);
    }

    log.debug("Calculate next delay");
    Integer delay = findClosestPoint(desiredTps, threadDelayStats.row(threadCount));

    delay = checkDelayInRange(delay);
    return WorkloadConfiguration.with(threadCount, delay);

}

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:org.kuali.kpme.tklm.time.util.TKUtilsTest.java

@Test
public void testConvertMillisToDays() throws Exception {
    Long millis = 86400000L;/*from   ww w  . j  av a 2  s . c o  m*/
    BigDecimal days = TKUtils.convertMillisToDays(millis);
    Assert.assertEquals("Wrong Days", 1, days.intValue());
}