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:burstcoin.jminer.JMinerCommandLine.java

private void initApplicationListeners() {
    context.addApplicationListener(new ApplicationListener<RoundFinishedEvent>() {
        @Override//from   w  w  w.  j ava  2s.  c  om
        public void onApplicationEvent(RoundFinishedEvent event) {
            previousRemainingCapacity = 0;
            previousElapsedTime = 0;

            long s = event.getRoundTime() / 1000;
            long ms = event.getRoundTime() % 1000;

            String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A"
                    : String.valueOf(event.getBestCommittedDeadline());
            LOG.info("FINISH block '" + event.getBlockNumber() + "', " + "best deadline '" + bestDeadline
                    + "', " + "round time '" + s + "s " + ms + "ms'");
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundStoppedEvent>() {
        @Override
        public void onApplicationEvent(RoundStoppedEvent event) {
            previousRemainingCapacity = 0;
            previousElapsedTime = 0;

            long s = event.getElapsedTime() / 1000;
            long ms = event.getElapsedTime() % 1000;

            BigDecimal totalCapacity = new BigDecimal(event.getCapacity());
            BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32);
            BigDecimal progress = factor
                    .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity()));
            int percentage = (int) Math.ceil(progress.doubleValue() * 100);
            percentage = percentage > 100 ? 100 : percentage;

            String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A"
                    : String.valueOf(event.getBestCommittedDeadline());
            LOG.info("STOP block '" + event.getBlockNumber() + "', " + String.valueOf(percentage) + "% done, "
                    + "best deadline '" + bestDeadline + "', " + "elapsed time '" + s + "s " + ms + "ms'");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkLastWinnerEvent>() {
        @Override
        public void onApplicationEvent(NetworkLastWinnerEvent event) {
            if (blockNumber - 1 == event.getLastBlockNumber()) {
                LOG.info(
                        "      winner block '" + event.getLastBlockNumber() + "', '" + event.getWinner() + "'");
            } else {
                LOG.error("Error: NetworkLastWinnerEvent for block: " + event.getLastBlockNumber()
                        + " is outdated!");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkStateChangeEvent>() {
        @Override
        public void onApplicationEvent(NetworkStateChangeEvent event) {
            blockNumber = event.getBlockNumber();
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundStartedEvent>() {
        @Override
        public void onApplicationEvent(RoundStartedEvent event) {
            progressLogStep = NUMBER_OF_PROGRESS_LOGS_PER_ROUND;

            LOG.info("-------------------------------------------------------");
            LOG.info("START block '" + event.getBlockNumber() + "', " + "scoopNumber '" + event.getScoopNumber()
                    + "', " + "capacity '" + event.getCapacity() / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR
                    + " " + G_UNIT + "'");
            String target = event.getTargetDeadline() == Long.MAX_VALUE ? "N/A"
                    : String.valueOf(event.getTargetDeadline());
            LOG.info("      targetDeadline '" + target + "', " + "baseTarget '"
                    + String.valueOf(event.getBaseTarget()) + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderProgressChangedEvent>() {
        @Override
        public void onApplicationEvent(ReaderProgressChangedEvent event) {
            long logStepCapacity = event.getCapacity() / NUMBER_OF_PROGRESS_LOGS_PER_ROUND;

            if (event.getRemainingCapacity() < logStepCapacity * progressLogStep
                    || event.getRemainingCapacity() == 0) {
                progressLogStep--;

                // trigger garbage collection on every progress step
                System.gc();

                BigDecimal totalCapacity = new BigDecimal(event.getCapacity());
                BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32);
                BigDecimal progress = factor
                        .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity()));
                int percentage = (int) Math.ceil(progress.doubleValue() * 100);
                percentage = percentage > 100 ? 100 : percentage;

                // calculate capacity
                long effMBPerSec = 0;
                if (previousRemainingCapacity > 0) {
                    long effDoneBytes = previousRemainingCapacity - event.getRemainingCapacity();

                    // calculate current reading speed (since last info)
                    long effBytesPerMs = (effDoneBytes / 4096) / (event.getElapsedTime() - previousElapsedTime);
                    effMBPerSec = (effBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR;
                }

                // calculate capacity
                long doneBytes = event.getCapacity() - event.getRemainingCapacity();
                long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR;
                long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR;

                // calculate reading speed (average)
                long averageBytesPerMs = (doneBytes / 4096) / event.getElapsedTime();
                long averageMBPerSec = (averageBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR;

                previousRemainingCapacity = event.getRemainingCapacity();
                previousElapsedTime = event.getElapsedTime();

                LOG.info(String.valueOf(percentage) + "% done (" + doneTB + T_UNIT + " " + doneGB + G_UNIT
                        + "), avg.'" + averageMBPerSec + " " + M_UNIT + "/s'"
                        + (effMBPerSec > 0 ? ", eff.'" + effMBPerSec + " " + M_UNIT + "/s'" : ""));
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundSingleResultEvent>() {
        @Override
        public void onApplicationEvent(RoundSingleResultEvent event) {
            LOG.info("dl '" + event.getCalculatedDeadline() + "' send ("
                    + (event.isPoolMining() ? "pool" : "solo") + ")");
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundSingleResultSkippedEvent>() {
        @Override
        public void onApplicationEvent(RoundSingleResultSkippedEvent event) {
            LOG.info(
                    "dl '" + event.getCalculatedDeadline() + "' > '" + event.getTargetDeadline() + "' skipped");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkResultConfirmedEvent>() {
        @Override
        public void onApplicationEvent(NetworkResultConfirmedEvent event) {
            LOG.info("dl '" + event.getDeadline() + "' confirmed!  [ " + getDeadlineTime(event.getDeadline())
                    + " ]");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkDevResultConfirmedEvent>() {
        @Override
        public void onApplicationEvent(NetworkDevResultConfirmedEvent event) {
            LOG.info("devPool response '" + event.getResponse() + "', block '" + event.getBlockNumber() + "'");
            for (DevPoolResult devPoolResult : event.getDevPoolResults()) {
                LOG.info("dl '" + devPoolResult.getCalculatedDeadline() + "' successful committed!  [ "
                        + getDeadlineTime(devPoolResult.getCalculatedDeadline()) + " ]");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkResultErrorEvent>() {
        @Override
        public void onApplicationEvent(NetworkResultErrorEvent event) {
            LOG.info("strange dl result '" + event.getStrangeDeadline() + "', calculated '"
                    + event.getCalculatedDeadline() + "' " + "block '" + event.getBlockNumber() + "' nonce '"
                    + event.getNonce() + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderCorruptFileEvent>() {
        @Override
        public void onApplicationEvent(ReaderCorruptFileEvent event) {
            LOG.info("strange dl source '" + event.getFilePath() + "' (try replotting!?)");
            LOG.info("strange dl file chunks '" + event.getNumberOfChunks() + "', " + "parts per chunk '"
                    + event.getNumberOfParts() + "', " + "block '" + event.getBlockNumber() + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderDriveFinishEvent>() {
        @Override
        public void onApplicationEvent(ReaderDriveFinishEvent event) {
            if (blockNumber == event.getBlockNumber()) {
                // calculate capacity
                long doneBytes = event.getSize();
                long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR;
                long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR;

                long s = event.getTime() / 1000;
                long ms = event.getTime() % 1000;

                LOG.info("read '" + event.getDirectory() + "' (" + doneTB + T_UNIT + " " + doneGB + G_UNIT
                        + ") in '" + s + "s " + ms + "ms'");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderDriveInterruptedEvent>() {
        @Override
        public void onApplicationEvent(ReaderDriveInterruptedEvent event) {
            LOG.info("stopped '" + event.getDirectory() + "' for block '" + event.getBlockNumber() + "'.");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkPoolInfoEvent>() {
        @Override
        public void onApplicationEvent(NetworkPoolInfoEvent event) {
            String value = event.getPoolBalanceNQT();
            String amount = value.length() > 8 ? value.substring(0, value.length() - 8) : value;
            value = event.getPoolForgedBalanceNQT();
            String totalForget = value.length() > 8 ? value.substring(0, value.length() - 8) : value;
            LOG.info("-------------------------------------------------------");
            LOG.info("POOL account '" + event.getPoolAccountRS() + "', assigned miners '"
                    + event.getPoolNumberOfMiningAccounts() + "'");
            LOG.info("     balance '" + amount + " BURST', total mined '" + totalForget + " BURST'");
        }
    });
}

From source file:org.multibit.utils.CSMiscUtils.java

public static String getFormattedDisplayString(CSAsset asset, BigDecimal d) {
    if (asset == null)
        return "";
    // FIXME: TODO: Format the string, separate method to do it.
    /*/*w w  w  . j av  a  2  s  .co m*/
     https://github.com/mastercoin-MSC/spec/blob/master/AssetIssuanceStandard.md
     "format": "* dollars",
     "format_1": "1 dollar",
     */
    String result = d.toPlainString(); // + " units"; // default
    if (0 == d.compareTo(BigDecimal.ONE)) {
        String fmt = asset.getFormat1();
        if (fmt != null && fmt.trim().length() != 0) {
            result = fmt;
            return result;
        }
    }

    // If value is not 1, or value is 1 but format_1 does not exist, use format.
    String fmt = asset.getFormat();
    // watch out, fmt can be empty string
    if (fmt != null && fmt.trim().length() != 0
            && org.apache.commons.lang3.StringUtils.countMatches(fmt, "*") == 1) {
        result = fmt.replaceFirst("\\*", d.toPlainString());
    }
    return result;
}

From source file:pe.gob.mef.gescon.hibernate.impl.WikiDaoImpl.java

@Override
public List<HashMap> getConcimientosVinculados(HashMap filters) {
    String nconocimientoid = (String) filters.get("nconocimientoid");
    String ntipoconocimientoid = (String) filters.get("ntipoconocimientoid");
    Boolean flag = (Boolean) filters.get("flag");
    Object object = null;//from   w w  w  . j a  va2s  . com
    final StringBuilder sql = new StringBuilder();
    if (StringUtils.isNotBlank(ntipoconocimientoid)
            && (ntipoconocimientoid.equals("3") || ntipoconocimientoid.equals("4")
                    || ntipoconocimientoid.equals("5") || ntipoconocimientoid.equals("6"))) {
        sql.append("SELECT ");
        sql.append(
                "    a.nvinculoid as ID, a.nconocimientovinc as IDCONOCIMIENTO, '' AS NUMERO, b.vtitulo AS NOMBRE, b.vdescripcion AS SUMILLA, ");
        sql.append("    b.ncategoriaid AS IDCATEGORIA, c.vnombre AS CATEGORIA, b.dfechacreacion AS FECHA, ");
        sql.append("    b.ntpoconocimientoid AS IDTIPOCONOCIMIENTO, e.vnombre AS TIPOCONOCIMIENTO, ");
        sql.append("    b.nsituacionid AS IDESTADO, d.vnombre AS ESTADO ");
        sql.append("FROM TVINCULO a ");
        sql.append("INNER JOIN TCONOCIMIENTO b ");
        sql.append("    INNER JOIN MTCATEGORIA c ON b.ncategoriaid = c.ncategoriaid ");
        sql.append("    INNER JOIN MTSITUACION d ON b.nsituacionid = d.nsituacionid ");
        sql.append("    INNER JOIN MTTIPO_CONOCIMIENTO e ON b.ntpoconocimientoid = e.ntpoconocimientoid ");
        sql.append("ON a.nconocimientovinc = b.nconocimientoid ");
        sql.append("AND a.ntipoconocimientovinc = b.ntpoconocimientoid ");
        sql.append("AND b.nactivo = :ACTIVO ");
        sql.append("WHERE a.nconocimientoid = ").append(nconocimientoid).append(" ");
        if (flag) {
            sql.append("AND a.ntipoconocimientovinc = ").append(ntipoconocimientoid).append(" ");
        }
        sql.append("ORDER BY 7 DESC ");
    }
    if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("2")) {
        sql.append("SELECT ");
        sql.append(
                "    a.nvinculoid as ID, a.nconocimientovinc as IDCONOCIMIENTO, '' AS NUMERO, b.vasunto AS NOMBRE , b.vdetalle AS SUMILLA, ");
        sql.append("    b.ncategoriaid AS IDCATEGORIA, c.vnombre AS CATEGORIA, b.dfechacreacion AS FECHA, ");
        sql.append("    2 AS IDTIPOCONOCIMIENTO, 'Preguntas y Respuestas' AS TIPOCONOCIMIENTO, ");
        sql.append("    b.nsituacionid AS IDESTADO, d.vnombre AS ESTADO ");
        sql.append("FROM TVINCULO a ");
        sql.append("INNER JOIN TPREGUNTA b ");
        sql.append("    INNER JOIN MTCATEGORIA c ON b.ncategoriaid = c.ncategoriaid ");
        sql.append("    INNER JOIN MTSITUACION d ON b.nsituacionid = d.nsituacionid ");
        sql.append("ON a.nconocimientovinc = b.npreguntaid ");
        sql.append("AND a.ntipoconocimientovinc = 2 ");
        sql.append("AND b.nactivo = :ACTIVO ");
        sql.append("WHERE a.nconocimientoid = ").append(nconocimientoid).append(" ");
        sql.append("ORDER BY 7 DESC ");
    }
    if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("1")) {
        sql.append("SELECT ");
        sql.append(
                "    a.nvinculoid as ID, a.nconocimientovinc as IDCONOCIMIENTO, b.vnumero AS NUMERO, b.vnombre AS NOMBRE , b.vsumilla AS SUMILLA, ");
        sql.append("    b.ncategoriaid AS IDCATEGORIA, c.vnombre AS CATEGORIA, b.dfechacreacion AS FECHA, ");
        sql.append("    1 AS IDTIPOCONOCIMIENTO, 'Base Legal' AS TIPOCONOCIMIENTO, ");
        sql.append("    b.nestadoid AS IDESTADO, d.vnombre AS ESTADO ");
        sql.append("FROM TVINCULO a ");
        sql.append("INNER JOIN TBASELEGAL b ");
        sql.append("    INNER JOIN MTCATEGORIA c ON b.ncategoriaid = c.ncategoriaid ");
        sql.append("    INNER JOIN MTESTADO_BASELEGAL d ON b.nestadoid = d.nestadoid ");
        sql.append("ON a.nconocimientovinc = b.nbaselegalid ");
        sql.append("AND a.ntipoconocimientovinc = 1 ");
        sql.append("AND b.nactivo = :ACTIVO ");
        sql.append("WHERE a.nconocimientoid = ").append(nconocimientoid).append(" ");
        sql.append("ORDER BY 7 DESC ");
    }
    try {
        object = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(sql.toString());
                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                if (StringUtils.isNotBlank(sql.toString())) {
                    query.setParameter("ACTIVO", BigDecimal.ONE);
                }
                return query.list();
            }
        });
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return (List<HashMap>) object;
}

From source file:org.fede.calculator.IndexTest.java

public void historicDollar() {

    YearMonth latestData = Inflation.USD_INFLATION.getTo();
    final int todayMonth = latestData.getMonth();
    final int todayYear = latestData.getYear();
    final MoneyAmount oneDollar = new MoneyAmount(BigDecimal.ONE, "USD");
    final String ars = "ARS";

    final MoneyAmountSeries historicDollar = ARS_INFLATION.adjust(
            ForeignExchanges.USD_ARS.exchange(USD_INFLATION.adjust(oneDollar, todayYear, todayMonth), ars),
            todayYear, todayMonth);/*  w  w w. j  a  va2  s . c om*/

    YearMonth comparisonYM = new YearMonth(2004, 1);

    MoneyAmount oneDollarInDollarInComparisonYM = ARS_INFLATION.adjust(
            ForeignExchanges.getForeignExchange(oneDollar.getCurrency(), ars).exchange(
                    USD_INFLATION.adjust(oneDollar, latestData.getYear(), latestData.getMonth(),
                            comparisonYM.getYear(), comparisonYM.getMonth()),
                    ars, comparisonYM.getYear(), comparisonYM.getMonth()),
            comparisonYM.getYear(), comparisonYM.getMonth(), todayYear, todayMonth);

    assertEquals(oneDollarInDollarInComparisonYM, historicDollar.getAmount(comparisonYM));

}

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

public void save(ActionEvent event) {
    try {/*from  w  w w .j  a v a  2 s .  c  o  m*/
        if (CollectionUtils.isEmpty(this.getListaPolitica())) {
            this.setListaPolitica(Collections.EMPTY_LIST);
        }
        Politica politica = new Politica();
        politica.setNmoduloid(this.getModuloid());
        politica.setVnombre(this.getNombre());
        politica.setVdescripcion(this.getDescripcion());
        if (!errorValidation(politica)) {
            politica.setVnombre(StringUtils.upperCase(this.getNombre().trim()));
            politica.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim()));
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();
            PoliticaService service = (PoliticaService) ServiceFinder.findBean("PoliticaService");
            politica.setNpoliticaid(service.getNextPK());
            politica.setNactivo(BigDecimal.ONE);
            politica.setDfechacreacion(new Date());
            politica.setVusuariocreacion(user.getVlogin());
            service.saveOrUpdate(politica);
            this.setListaPolitica(service.getPoliticas());
            this.cleanAttributes();
            RequestContext.getCurrentInstance().execute("PF('newDialog').hide();");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:pe.gob.mef.gescon.hibernate.impl.BaseLegalDaoImpl.java

@Override
public List<HashMap> getTbaselegalesNotLinkedById(final BigDecimal id) throws Exception {
    final StringBuilder sql = new StringBuilder();
    Object object = null;//from  w  w w .  java 2 s.co  m
    try {
        sql.append(
                "SELECT a.nbaselegalid AS ID, a.vnumero AS NUMERO, a.vnombre AS NOMBRE, a.vsumilla AS SUMILLA, ");
        sql.append(
                "       a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, ");
        sql.append("       a.nestadoid AS IDESTADO, c.vnombre AS ESTADO ");
        sql.append("FROM TBASELEGAL a ");
        sql.append("INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
        sql.append("INNER JOIN MTESTADO_BASELEGAL c ON a.nestadoid = c.nestadoid ");
        sql.append("WHERE a.nactivo = :ACTIVO ");
        sql.append("AND a.nestadoid IN (:ESTADO_PUBLICADO, :ESTADO_CONCORDADO, :ESTADO_MODIFICADA) ");
        if (id != null) {
            sql.append("AND a.nbaselegalid <> :ID ");
            sql.append(
                    "AND a.nbaselegalid NOT IN(SELECT d.nbaselegalvinculadaid FROM TVINCULO_BASELEGAL d WHERE d.nbaselegalid = :ID) ");
        }
        sql.append("ORDER BY a.vnumero ");

        object = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(sql.toString());
                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                query.setParameter("ACTIVO", BigDecimal.ONE);
                query.setParameter("ESTADO_PUBLICADO", Constante.ESTADO_BASELEGAL_PUBLICADO);
                query.setParameter("ESTADO_CONCORDADO", Constante.ESTADO_BASELEGAL_CONCORDADO);
                query.setParameter("ESTADO_MODIFICADA", Constante.ESTADO_BASELEGAL_MODIFICADA);
                if (id != null) {
                    query.setParameter("ID", id);
                }
                return query.list();
            }
        });
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return (List<HashMap>) object;
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testMigration() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {/*from  ww w  . j  a v  a 2 s  . c  o  m*/
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);

        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(buildTimestamp, eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(AVAILABLE_SEATS, tickets.size());
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

/**
 * Verifies that the stock is updated correctly if referred to by two different items in a transaction.
 *///w w w.  j  a  va  2  s  . c  om
@Test
public void testMultipleStockUpdatesInTxn() {
    final List<FinancialAct> acts = new ArrayList<FinancialAct>(createInvoice());
    final FinancialAct item1 = acts.get(1);
    final FinancialAct item2 = FinancialTestHelper.createChargeItem(CustomerAccountArchetypes.INVOICE_ITEM,
            patient, product, BigDecimal.ONE);
    addStockLocation(item2);
    acts.add(item2);

    BigDecimal initialQuantity = BigDecimal.ZERO;
    BigDecimal quantity = BigDecimal.valueOf(5);

    item1.setQuantity(quantity);
    item2.setQuantity(quantity);

    checkEquals(initialQuantity, getStock(stockLocation, product));
    BigDecimal expected = getQuantity(initialQuantity, quantity.add(quantity), false);

    TransactionTemplate template = new TransactionTemplate(txnManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            save(acts);
        }
    });
    checkEquals(expected, getStock(stockLocation, product));

    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            item1.setQuantity(BigDecimal.ONE);
            save(item1);
            remove(item2);
        }
    });
    expected = getQuantity(initialQuantity, BigDecimal.ONE, false);
    checkEquals(expected, getStock(stockLocation, product));
}

From source file:com.msopentech.odatajclient.proxy.InvokeTestITCase.java

@Test
public void changeProductDimensions() {
    // 0. create a product
    final Integer id = 101;

    Product product = container.getProduct().newProduct();
    product.setProductId(id);//from w ww. ja v  a  2s  .  c  o  m
    product.setDescription("New product");

    final Dimensions origDimensions = new Dimensions();
    origDimensions.setDepth(BigDecimal.ZERO);
    origDimensions.setHeight(BigDecimal.ZERO);
    origDimensions.setWidth(BigDecimal.ZERO);
    product.setDimensions(origDimensions);

    container.flush();

    product = container.getProduct().get(id);
    assertNotNull(product);
    assertEquals(id, product.getProductId());
    assertEquals(BigDecimal.ZERO, product.getDimensions().getDepth());
    assertEquals(BigDecimal.ZERO, product.getDimensions().getHeight());
    assertEquals(BigDecimal.ZERO, product.getDimensions().getWidth());

    try {
        // 1. invoke action bound to the product just created
        final Dimensions newDimensions = new Dimensions();
        newDimensions.setDepth(BigDecimal.ONE);
        newDimensions.setHeight(BigDecimal.ONE);
        newDimensions.setWidth(BigDecimal.ONE);

        product.changeProductDimensions(newDimensions);

        // 2. check that invoked action has effectively run
        product = container.getProduct().get(id);
        assertEquals(BigDecimal.ONE, product.getDimensions().getDepth());
        assertEquals(BigDecimal.ONE, product.getDimensions().getHeight());
        assertEquals(BigDecimal.ONE, product.getDimensions().getWidth());
    } finally {
        // 3. remove the test product
        container.getProduct().delete(product.getProductId());
        container.flush();
    }
}

From source file:org.apache.hadoop.hbase.io.hfile.slab.SlabCache.java

/**
 * A way of allocating the desired amount of Slabs of each particular size.
 *
 * This reads two lists from conf, hbase.offheap.slab.proportions and
 * hbase.offheap.slab.sizes.//  w  w  w  . j a  v a  2 s . c  o  m
 *
 * The first list is the percentage of our total space we allocate to the
 * slabs.
 *
 * The second list is blocksize of the slabs in bytes. (E.g. the slab holds
 * blocks of this size).
 *
 * @param conf Configuration file.
 */
public void addSlabByConf(Configuration conf) {
    // Proportions we allocate to each slab of the total size.
    String[] porportions = conf.getStrings(SLAB_CACHE_PROPORTIONS_KEY, "0.80", "0.20");
    String[] sizes = conf.getStrings(SLAB_CACHE_SIZES_KEY, Long.valueOf(avgBlockSize * 11 / 10).toString(),
            Long.valueOf(avgBlockSize * 21 / 10).toString());

    if (porportions.length != sizes.length) {
        throw new IllegalArgumentException("SlabCache conf not "
                + "initialized, error in configuration. hbase.offheap.slab.proportions specifies "
                + porportions.length + " slabs while hbase.offheap.slab.sizes specifies " + sizes.length
                + " slabs " + "offheapslabporportions and offheapslabsizes");
    }
    /*
     * We use BigDecimals instead of floats because float rounding is annoying
     */

    BigDecimal[] parsedProportions = stringArrayToBigDecimalArray(porportions);
    BigDecimal[] parsedSizes = stringArrayToBigDecimalArray(sizes);

    BigDecimal sumProportions = new BigDecimal(0);
    for (BigDecimal b : parsedProportions) {
        /* Make sure all proportions are greater than 0 */
        Preconditions.checkArgument(b.compareTo(BigDecimal.ZERO) == 1,
                "Proportions in hbase.offheap.slab.proportions must be greater than 0!");
        sumProportions = sumProportions.add(b);
    }

    /* If the sum is greater than 1 */
    Preconditions.checkArgument(sumProportions.compareTo(BigDecimal.ONE) != 1,
            "Sum of all proportions in hbase.offheap.slab.proportions must be less than 1");

    /* If the sum of all proportions is less than 0.99 */
    if (sumProportions.compareTo(new BigDecimal("0.99")) == -1) {
        LOG.warn("Sum of hbase.offheap.slab.proportions is less than 0.99! Memory is being wasted");
    }
    for (int i = 0; i < parsedProportions.length; i++) {
        int blockSize = parsedSizes[i].intValue();
        int numBlocks = new BigDecimal(this.size).multiply(parsedProportions[i])
                .divide(parsedSizes[i], BigDecimal.ROUND_DOWN).intValue();
        addSlab(blockSize, numBlocks);
    }
}