Example usage for java.math BigDecimal ROUND_DOWN

List of usage examples for java.math BigDecimal ROUND_DOWN

Introduction

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

Prototype

int ROUND_DOWN

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

Click Source Link

Document

Rounding mode to round towards zero.

Usage

From source file:ch.algotrader.entity.security.SecurityFamilyImpl.java

@Override
public double roundDown(String broker, double price) {
    return RoundUtil.roundToNextN(price, getTickSize(broker, price, false), BigDecimal.ROUND_DOWN);
}

From source file:at.illecker.hama.hybrid.examples.summation.SummationBSP.java

static BigDecimal writeSummationInputFile(FileSystem fs, Path dir, int fileCount) throws IOException {

    BigDecimal sum = new BigDecimal(0);
    Random rand = new Random();
    double rangeMin = 0;
    double rangeMax = 100;

    for (int i = 0; i < fileCount; i++) {
        DataOutputStream out = fs.create(new Path(dir, "part" + i));

        // loop between 50 and 149 times
        for (int j = 0; j < rand.nextInt(100) + 50; j++) {
            // generate key value pair inputs
            double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();

            String truncatedValue = new BigDecimal(randomValue)
                    .setScale(DOUBLE_PRECISION, BigDecimal.ROUND_DOWN).toString();

            String line = "key" + (j + 1) + "\t" + truncatedValue + "\n";
            out.writeBytes(line);//from w w  w  .  j a va  2s  .co m

            sum = sum.add(new BigDecimal(truncatedValue));
            LOG.debug("input[" + j + "]: '" + line + "' sum: " + sum.toString());
        }
        out.close();
    }
    return sum;
}

From source file:Main.java

/**
 * Compute the integral root of x to a given scale, x >= 0.
 * Use Newton's algorithm./*from  ww  w  .j  a v  a2  s.c om*/
 * @param x the value of x
 * @param index the integral root value
 * @param scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal intRoot(BigDecimal x, long index, int scale) {
    // Check that x >= 0.
    if (x.signum() < 0) {
        throw new IllegalArgumentException("x < 0");
    }

    int sp1 = scale + 1;
    BigDecimal n = x;
    BigDecimal i = BigDecimal.valueOf(index);
    BigDecimal im1 = BigDecimal.valueOf(index - 1);
    BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);
    BigDecimal xPrev;

    // The initial approximation is x/index.
    x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN);

    // Loop until the approximations converge
    // (two successive approximations are equal after rounding).
    do {
        // x^(index-1)
        BigDecimal xToIm1 = intPower(x, index - 1, sp1);

        // x^index
        BigDecimal xToI = x.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // n + (index-1)*(x^index)
        BigDecimal numerator = n.add(im1.multiply(xToI)).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // (index*(x^(index-1))
        BigDecimal denominator = i.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
        xPrev = x;
        x = numerator.divide(denominator, sp1, BigDecimal.ROUND_DOWN);

        Thread.yield();
    } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0);

    return x;
}

From source file:com.opengamma.bloombergexample.loader.DemoEquityOptionCollarPortfolioLoader.java

private void addNodes(ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying,
        Period[] expiries) {/*w w  w.  j  a v a  2  s .c  om*/
    ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying);
    ManageableSecurity underlyingSecurity = null;
    if (includeUnderlying) {
        underlyingSecurity = getOrLoadEquity(ticker);
    }

    ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker)
            : underlyingSecurity.getExternalIdBundle();
    HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle);
    double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo);
    Set<ExternalId> optionChain = getOptionChain(ticker);

    //TODO: reuse positions/nodes?
    String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName();
    String formattedName = MessageFormatter.format("[{}] {}", underlying, longName);
    ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName);

    BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike),
            BigDecimal.ROUND_HALF_EVEN);

    if (includeUnderlying) {
        addPosition(equityNode, underlyingAmount, ticker);
    }

    TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>();
    for (ExternalId optionTicker : optionChain) {
        s_logger.debug("Got option {}", optionTicker);

        BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker);
        s_logger.debug("Got option info {}", optionInfo);

        LocalDate key = optionInfo.getExpiry();
        Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key);
        if (set == null) {
            set = new HashSet<BloombergTickerParserEQOption>();
            optionsByExpiry.put(key, set);
        }
        set.add(optionInfo);
    }
    Set<ExternalId> tickersToLoad = new HashSet<ExternalId>();

    BigDecimal expiryCount = BigDecimal.valueOf(expiries.length);
    BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN);
    BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE);
    int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue();

    for (int i = 0; i < expiries.length; i++) {
        Period bucketPeriod = expiries[i];

        ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1));

        LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run
        LocalDate targetExpiry = nowish.plus(bucketPeriod);
        LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry);
        if (chosenExpiry == null) {
            s_logger.warn("No options for {} on {}", targetExpiry, underlying);
            continue;
        }
        s_logger.info("Using time {} for bucket {} ({})",
                new Object[] { chosenExpiry, bucketPeriod, targetExpiry });

        Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry);
        TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (BloombergTickerParserEQOption option : optionsAtExpiry) {
            //        s_logger.info("option {}", option);
            double key = option.getStrike();
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key);
            if (pair == null) {
                pair = Pair.of(null, null);
            }
            if (option.getOptionType() == OptionType.CALL) {
                pair = Pair.of(option, pair.getSecond());
            } else {
                pair = Pair.of(pair.getFirst(), option);
            }
            optionsByStrike.put(key, pair);
        }

        //cascading collar?
        BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry;

        s_logger.info(" est strike {}", estimatedCurrentStrike);
        Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]);

        int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike);
        if (strikeIndex < 0) {
            strikeIndex = -(1 + strikeIndex);
        }
        s_logger.info("strikes length {} index {} strike of index {}",
                new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex),
                        Double.valueOf(strikes[strikeIndex]) });

        int minIndex = strikeIndex - _numOptions;
        minIndex = Math.max(0, minIndex);
        int maxIndex = strikeIndex + _numOptions;
        maxIndex = Math.min(strikes.length - 1, maxIndex);

        s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex));
        StringBuffer sb = new StringBuffer("strikes: [");
        for (int j = minIndex; j <= maxIndex; j++) {
            sb.append(" ");
            sb.append(strikes[j]);
        }
        sb.append(" ]");
        s_logger.info(sb.toString());

        //Short Calls
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = minIndex; j < strikeIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            calls.add(pair);
        }
        spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying,
                calls.size());

        // Long Puts
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = strikeIndex + 1; j <= maxIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            puts.add(pair);
        }
        spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying,
                puts.size());

        if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) {
            equityNode.addChildNode(bucketNode); //Avoid generating empty nodes   
        }
    }

    for (ExternalId optionTicker : tickersToLoad) {
        ManageableSecurity loaded = getOrLoadSecurity(optionTicker);
        if (loaded == null) {
            throw new OpenGammaRuntimeException("Unexpected option type " + loaded);
        }

        //TODO [LAPANA-29] Should be able to do this for index options too
        if (includeUnderlying) {
            try {
                HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker,
                        loaded.getExternalIdBundle());
                if (loadedTs == null) {
                    throw new OpenGammaRuntimeException("Failed to get time series for " + loaded);
                }
            } catch (Exception ex) {
                s_logger.error("Failed to get time series for " + loaded, ex);
            }
        }
    }

    if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) {
        rootNode.addChildNode(equityNode);
    }
}

From source file:com.opengamma.examples.bloomberg.loader.DemoEquityOptionCollarPortfolioLoader.java

private void addNodes(final ManageablePortfolioNode rootNode, final String underlying,
        final boolean includeUnderlying, final Period[] expiries) {
    final ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying);
    ManageableSecurity underlyingSecurity = null;
    if (includeUnderlying) {
        underlyingSecurity = getOrLoadEquity(ticker);
    }/*from ww  w  .  java 2s.c  o m*/

    final ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker)
            : underlyingSecurity.getExternalIdBundle();
    final HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle);
    final double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo);
    final Set<ExternalId> optionChain = getOptionChain(ticker);

    //TODO: reuse positions/nodes?
    final String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName();
    final String formattedName = MessageFormatter.format("[{}] {}", underlying, longName).getMessage();
    final ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName);

    final BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike),
            BigDecimal.ROUND_HALF_EVEN);

    if (includeUnderlying) {
        addPosition(equityNode, underlyingAmount, ticker);
    }

    final TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>();
    for (final ExternalId optionTicker : optionChain) {
        s_logger.debug("Got option {}", optionTicker);

        final BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption
                .getOptionParser(optionTicker);
        s_logger.debug("Got option info {}", optionInfo);

        final LocalDate key = optionInfo.getExpiry();
        Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key);
        if (set == null) {
            set = new HashSet<BloombergTickerParserEQOption>();
            optionsByExpiry.put(key, set);
        }
        set.add(optionInfo);
    }
    final Set<ExternalId> tickersToLoad = new HashSet<ExternalId>();

    final BigDecimal expiryCount = BigDecimal.valueOf(expiries.length);
    final BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN);
    final BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE);
    int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue();

    for (final Period bucketPeriod : expiries) {
        final ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(
                bucketPeriod.toString().substring(1));

        final LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run
        final LocalDate targetExpiry = nowish.plus(bucketPeriod);
        final LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry);
        if (chosenExpiry == null) {
            s_logger.info("No options for {} on {}", targetExpiry, underlying);
            continue;
        }
        s_logger.info("Using time {} for bucket {} ({})",
                new Object[] { chosenExpiry, bucketPeriod, targetExpiry });

        final Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry);
        final TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<>();
        for (final BloombergTickerParserEQOption option : optionsAtExpiry) {
            //        s_logger.info("option {}", option);
            final double key = option.getStrike();
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key);
            if (pair == null) {
                pair = Pair.of(null, null);
            }
            if (option.getOptionType() == OptionType.CALL) {
                pair = Pair.of(option, pair.getSecond());
            } else {
                pair = Pair.of(pair.getFirst(), option);
            }
            optionsByStrike.put(key, pair);
        }

        //cascading collar?
        final BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry;

        s_logger.info(" est strike {}", estimatedCurrentStrike);
        final Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]);

        int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike);
        if (strikeIndex < 0) {
            strikeIndex = -(1 + strikeIndex);
        }
        s_logger.info("strikes length {} index {} strike of index {}",
                new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex),
                        Double.valueOf(strikes[strikeIndex]) });

        int minIndex = strikeIndex - _numOptions;
        minIndex = Math.max(0, minIndex);
        int maxIndex = strikeIndex + _numOptions;
        maxIndex = Math.min(strikes.length - 1, maxIndex);

        s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex));
        final StringBuffer sb = new StringBuffer("strikes: [");
        for (int j = minIndex; j <= maxIndex; j++) {
            sb.append(" ");
            sb.append(strikes[j]);
        }
        sb.append(" ]");
        s_logger.info(sb.toString());

        //Short Calls
        final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = minIndex; j < strikeIndex; j++) {
            final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            calls.add(pair);
        }
        spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying,
                calls.size());

        // Long Puts
        final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = strikeIndex + 1; j <= maxIndex; j++) {
            final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            puts.add(pair);
        }
        spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying,
                puts.size());

        if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) {
            equityNode.addChildNode(bucketNode); //Avoid generating empty nodes
        }
    }

    for (final ExternalId optionTicker : tickersToLoad) {
        final ManageableSecurity loaded = getOrLoadSecurity(optionTicker);
        if (loaded == null) {
            throw new OpenGammaRuntimeException("Unexpected option type " + loaded);
        }

        //TODO [LAPANA-29] Should be able to do this for index options too
        if (includeUnderlying) {
            try {
                final HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker,
                        loaded.getExternalIdBundle());
                if (loadedTs == null) {
                    throw new OpenGammaRuntimeException("Failed to get time series for " + loaded);
                }
            } catch (final Exception ex) {
                s_logger.info("Failed to get time series for " + loaded, ex);
            }
        }
    }

    if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) {
        rootNode.addChildNode(equityNode);
    }
}

From source file:com.sfs.Formatter.java

/**
 * Gets the part number of months based on the number of weeks supplied.
 *
 * @param weeks the weeks value// www  .  j  av a  2  s.co m
 * @return the part months
 */
public static int getPartMonths(final int weeks) {

    BigDecimal bd = new BigDecimal(weeks / WEEKS_IN_MONTH);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);

    return (int) bd.intValue();
}

From source file:Armadillo.Analytics.Base.Precision.java

/**
 * Rounds the given non-negative value to the "nearest" integer. Nearest is
 * determined by the rounding method specified. Rounding methods are defined
 * in {@link BigDecimal}./*ww  w  . j a  v  a2  s. c o m*/
 *
 * @param unscaled Value to round.
 * @param sign Sign of the original, scaled value.
 * @param roundingMethod Rounding method, as defined in {@link BigDecimal}.
 * @return the rounded value.
 * @throws MathArithmeticException if an exact operation is required but result is not exact
 * @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
 * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
 */
private static double roundUnscaled(double unscaled, double sign, int roundingMethod)
        throws MathArithmeticException, MathIllegalArgumentException {
    switch (roundingMethod) {
    case BigDecimal.ROUND_CEILING:
        if (sign == -1) {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        } else {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_DOWN:
        unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        break;
    case BigDecimal.ROUND_FLOOR:
        if (sign == -1) {
            unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        } else {
            unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
        }
        break;
    case BigDecimal.ROUND_HALF_DOWN: {
        unscaled = FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_HALF_EVEN: {
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction > 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else if (fraction < 0.5) {
            unscaled = FastMath.floor(unscaled);
        } else {
            // The following equality test is intentional and needed for rounding purposes
            if (FastMath.floor(unscaled) / 2.0 == FastMath.floor(Math.floor(unscaled) / 2.0)) { // even
                unscaled = FastMath.floor(unscaled);
            } else { // odd
                unscaled = FastMath.ceil(unscaled);
            }
        }
        break;
    }
    case BigDecimal.ROUND_HALF_UP: {
        unscaled = FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY);
        double fraction = unscaled - FastMath.floor(unscaled);
        if (fraction >= 0.5) {
            unscaled = FastMath.ceil(unscaled);
        } else {
            unscaled = FastMath.floor(unscaled);
        }
        break;
    }
    case BigDecimal.ROUND_UNNECESSARY:
        if (unscaled != FastMath.floor(unscaled)) {
            throw new MathArithmeticException();
        }
        break;
    case BigDecimal.ROUND_UP:
        unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
        break;
    default:
        throw new MathIllegalArgumentException(LocalizedFormats.INVALID_ROUNDING_METHOD, roundingMethod,
                "ROUND_CEILING", BigDecimal.ROUND_CEILING, "ROUND_DOWN", BigDecimal.ROUND_DOWN, "ROUND_FLOOR",
                BigDecimal.ROUND_FLOOR, "ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN, "ROUND_HALF_EVEN",
                BigDecimal.ROUND_HALF_EVEN, "ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP, "ROUND_UNNECESSARY",
                BigDecimal.ROUND_UNNECESSARY, "ROUND_UP", BigDecimal.ROUND_UP);
    }
    return unscaled;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getAppLoadTimeAVG//from   w w w.  j  ava2 s  .c o  m
 * @return
 */
public double getAppLoadTimeAVG() {
    int decimalPlaces = 2;
    double loadTimeAVG = 0.0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(LOADTIME) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        loadTimeAVG = rs.getInt(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query number of events from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd = new BigDecimal(loadTimeAVG);
    bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
    loadTimeAVG = bd.doubleValue();

    return loadTimeAVG;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLatencyAverage/*from  w w  w.  j a v  a2s . c o m*/
 * 
 * @return Latency average
 */
private final double getAvailabilityAverage() {
    double availAvg = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(AVAILABILITY) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        availAvg = rs.getDouble(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd = new BigDecimal(availAvg);
    bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
    availAvg = bd.doubleValue();

    return availAvg;
}

From source file:org.meerkat.services.WebApp.java

/**
 * /*from w w  w.j  a v a 2s.  co  m*/
 * getLatencyIndicator
 * @return    1 if last latency higher than latency average
 *          -1 if last latency lower than latency average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLatencyIndicator() {
    double doubleLatencyAverage = getLatencyAverage();
    BigDecimal bd = new BigDecimal(doubleLatencyAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double latencyAverage = bd.doubleValue();

    // get the value of last event
    double lastLatency = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LATENCY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLatency = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLatency);
    bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN);
    lastLatency = bd1.doubleValue();

    if (lastLatency > latencyAverage) {
        return 1;
    } else if (lastLatency < latencyAverage) {
        return -1;
    }

    return 0;
}