List of usage examples for java.math BigDecimal valueOf
public static BigDecimal valueOf(double val)
From source file:net.sourceforge.fenixedu.domain.studentCurriculum.ExternalEnrolment.java
@Override final public BigDecimal getEctsCreditsForCurriculum() { return BigDecimal.valueOf(getEctsCredits()); }
From source file:org.spc.ofp.tubs.importer.TubsTripProcessor.java
protected Activity asTubsActivity(final DayLog dl) { if (null == dl) { return null; }// w ww . j a v a 2 s . co m Activity activity = new Activity(); final Integer activityId = DataCleaner.getPurseSeineActivity(dl.getS_act_id()); if (null != activityId) { activity.setActivityType(repo.findReferenceValueById(activityId)); } final Integer detectionId = DataCleaner.getPurseSeineDetection(dl.getDet_id()); if (null != detectionId) { activity.setDetectionMethod(repo.findReferenceValueById(detectionId)); } final Integer associationId = DataCleaner.getPurseSeineAssociation(dl.getSch_id()); if (null != associationId) { activity.setAssociationType(repo.findReferenceValueById(associationId)); } activity.setLocalTime(combine(dl.getActdate(), dl.getActtime())); activity.setUtcTime(combine(dl.getUtc_adate(), dl.getUtc_atime())); activity.setBeacon(dl.getBeacon()); activity.setComments(dl.getComment()); activity.setEezCode(dl.getEz_id()); BigDecimal fishingDays = null; if (null != dl.getFish_days()) { fishingDays = BigDecimal.valueOf(dl.getFish_days().doubleValue()).setScale(7); //fishingDays = new BigDecimal(dl.getFish_days()); } activity.setFishingDays(fishingDays); activity.setLatitude(dl.getLat_long()); activity.setLongitude(dl.getLon_long()); activity.setSeaState(asTubsSeaState(dl.getSea_id())); activity.setWindDirection(dl.getWinddir()); activity.setWindSpeed(dl.getWind_kts()); // Only set this for an appropriate activity // This is a shortcut for the referenceId ACTIVE/Fishing that currently has id = 1 if (null != dl.getS_act_id() && 1 == dl.getS_act_id().intValue()) { LOGGER.debug("Copying DayLog data into FishingSet"); activity.setFishingSet(asTubsFishingSet(dl)); } activity.setAuditEntry(new AuditEntry(dl.getEnteredby(), dl.getInserttime())); return activity; }
From source file:it.av.es.service.impl.OrderServiceHibernate.java
/** * {@inheritDoc}//from w w w .j a v a2 s.com */ @Override public Order calculatesCostsAndDiscount(Order o) { //ArrayList<ProductOrdered> newList = new ArrayList<ProductOrdered>(o.getProductsOrdered().size()); for (ProductOrdered p : o.getProductsOrdered()) { BigDecimal amount = new BigDecimal(0); Currency currency; int percentDiscount = 0; List<Price> prices = p.getProduct().getPrices(); //calculates the price and apply discount // per il cacolo somma tutti i prodotti dello stesso tipo int productAllOrder = o.getTotalProductforGivenProduct(p.getProduct()); // se il prodoptto appartiene ad una famigliam considera anche i prodotti di quella famiglia if (p.getProduct().getProductFamily() != null) { productAllOrder = o.getTotalProductforGivenProductFamily(p.getProduct().getProductFamily()); } for (Price price : prices) { if (productAllOrder >= price.getFromNumber() && productAllOrder <= price.getToNumber()) { amount = price.getAmount(); currency = price.getCurrency(); percentDiscount = price.getPercentDiscount(); } } if (amount == BigDecimal.ZERO) { throw new EasySendException("Price not available"); } p.setAmount(amount.multiply(BigDecimal.valueOf(p.getNumber()))); //apply discount if applicable if (o.getPaymentTypeP().getDiscount() > 0) { BigDecimal discount = ((p.getAmount().divide(BigDecimal.valueOf(100))) .multiply(BigDecimal.valueOf(o.getPaymentTypeP().getDiscount()))); p.setAmount(p.getAmount().subtract(discount)); percentDiscount = percentDiscount + o.getPaymentTypeP().getDiscount(); } p.setDiscount(percentDiscount); //add the productOrdered to the order // o.getProductsOrdered().add(p); //apply Discounts If Applicable //applyDiscountIfApplicable(order); //apply FreeShippingCost If Applicable } //o.setProductsOrdered(newList); //applyFreeShippingCostIfApplicable(o); return o; }
From source file:de.hybris.platform.b2b.services.impl.B2BMerchantCheckTest.java
@Test @Ignore("breaks in https://bamboo.hybris.com/download/HYBRISACCELERATORR-B2BACCELERATOR-BUILD, the test needs to be refactored.") public void shouldTriggerCreditAlertOnceForTimePeriod() throws Exception { /**/*from w w w. ja va2s . co m*/ * Create and order between 8000 - 10000 EUR for unit GC Sales DE Alert should be created for GC Sales Rep */ login("GC Sales DE Boss"); final OrderModel order = createOrder("GC Sales DE Boss", 900, OrderStatus.CREATED); b2bCartService.removeSessionCart(); Assert.assertNotNull(order); //Set up credit limit data for test - should not have alert sent date final B2BUnitModel unitLoggedIn = b2bUnitService.getUnitForUid("GC Sales DE"); final B2BCreditLimitModel creditLimit = unitLoggedIn.getCreditLimit(); creditLimit.setActive(Boolean.TRUE); creditLimit.setDateRange(B2BPeriodRange.DAY); creditLimit.setAmount(BigDecimal.valueOf(10000D)); creditLimit.setAlertThreshold(BigDecimal.valueOf(8000D)); creditLimit.setDatePeriod(null); creditLimit.setAlertSentDate(null); modelService.save(creditLimit); final B2BApprovalProcessModel b2bApprovalProcessModel = getB2BApprovalProcessModelForOrder(order); this.waitForProcessToEnd(b2bApprovalProcessModel.getCode(), 20000); this.modelService.refresh(order); this.modelService.refresh(b2bApprovalProcessModel); Assert.assertEquals(OrderStatus.APPROVED, order.getStatus()); Assert.assertEquals(ProcessState.SUCCEEDED, b2bApprovalProcessModel.getProcessState()); //Check Alert Sent Date exist now modelService.refresh(creditLimit); Assert.assertNotNull("AlertSendDate should have been set", creditLimit.getAlertSentDate()); // create a second order 100 total against the same cost center which makes the orders total of 9010 for the credit limit //the order still exceeds Alert Limit (8000) but the total of all orders is below credit limit (1000) final OrderModel order2 = createOrder("GC Sales DE Boss", 10, OrderStatus.CREATED); Assert.assertNotNull(order2); final B2BApprovalProcessModel b2bApprovalProcessModel2 = getB2BApprovalProcessModelForOrder(order2); this.waitForProcessToEnd(b2bApprovalProcessModel2.getCode(), 20000); this.modelService.refresh(order2); this.modelService.refresh(b2bApprovalProcessModel2); Assert.assertEquals(OrderStatus.APPROVED, order2.getStatus()); Assert.assertEquals(ProcessState.SUCCEEDED, b2bApprovalProcessModel2.getProcessState()); //Alert Sent Date was in past, so it's updated with Current Date modelService.refresh(creditLimit); Assert.assertNotNull("AlertSentDate should not be null", creditLimit.getAlertSentDate()); Assert.assertTrue(String.format("AlertSentDate %s shold be in the same day as %s", creditLimit.getAlertSentDate(), new Date()), DateUtils.isSameDay(creditLimit.getAlertSentDate(), new Date())); }
From source file:de.hybris.platform.configurablebundleservices.bundle.impl.FindBundlePricingWithCurrentPriceFactoryStrategyTest.java
@Test public void testOneTimeChargePricePlanWinsAgainstRule() { given(childCart.getBillingTime()).willReturn(oneTimeChargeBillingEvent); given(priceRule.getBillingEvent()).willReturn(oneTimeChargeBillingEvent); given(priceRule.getPrice()).willReturn(BigDecimal.valueOf(RULE_HIGH_PRICE.doubleValue())); given(commercePriceService.getOneTimeChargeEntryPlan(pricePlan, oneTimeChargeBillingEvent)) .willReturn(oneTimeChargeEntry); given(oneTimeChargeEntry.getPrice()).willReturn(ONE_TIME_CHARGE_PLAN_PRICE); given(childEntry.getBasePrice()).willReturn(BASE_PRICE); given(oneTimeChargeEntry.getId()).willReturn("oneTimeChargeEntry"); given(priceRule.getId()).willReturn("priceRule"); final List<DiscountValue> discountValues = Lists.newArrayList(); bundlePriceFactory.reduceOneTimePrice(pricePlan, priceRule, discountValues, currency, childEntry); assertEquals("", 1, discountValues.size()); final DiscountValue discount = discountValues.iterator().next(); assertEquals("", "oneTimeChargeEntry", discount.getCode()); assertEquals(BASE_PRICE.doubleValue() - ONE_TIME_CHARGE_PLAN_PRICE.doubleValue(), discount.getValue(), 0.005);// w ww . j a va 2 s .c o m }
From source file:net.sourceforge.fenixedu.domain.studentCurriculum.ExternalEnrolment.java
@Override final public BigDecimal getWeigthForCurriculum() { return BigDecimal.valueOf(getWeigth()); }
From source file:it.geosolutions.geoserver.rest.encoder.feature.GSFeatureEncoderTest.java
@Test public void testModifyFeature() { GSFeatureTypeEncoder encoder = new GSFeatureTypeEncoder(); encoder.addKeyword("KEYWORD_1"); encoder.addKeyword("KEYWORD_1", "LAN_1", "VOCAB_1"); assertTrue(encoder.delKeyword("KEYWORD_1", "LAN_1", "VOCAB_1")); encoder.addKeyword("..."); encoder.addKeyword("KEYWORD_N"); assertFalse(encoder.delKeyword("KEYWORD_M")); encoder.addKeyword("KEYWORD_2"); assertFalse(encoder.delKeyword("KEYWORD_2", "LAN_1", "VOCAB_1")); assertTrue(encoder.delKeyword("KEYWORD_2")); // metadataLinkInfo encoder.addMetadataLinkInfo("text/xml", "ISO19115:2003", "http://www.organization.org/metadata1"); encoder.addMetadataLinkInfo("text/html", "ISO19115:2003", "http://www.organization.org/metadata2"); assertTrue(encoder.delMetadataLinkInfo("http://www.organization.org/metadata2")); assertFalse(encoder.delMetadataLinkInfo("http://www.organization.org/metadata3")); // dimensions final GSFeatureDimensionInfoEncoder elevationDimension = new GSFeatureDimensionInfoEncoder( "elevation_field"); // if (LOGGER.isInfoEnabled()) // LOGGER.info(encoder.toString()); final String metadata = "elevation"; encoder.setMetadataDimension(metadata, elevationDimension); elevationDimension.setPresentation(Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(10)); if (LOGGER.isInfoEnabled()) LOGGER.info(encoder.toString()); assertTrue(encoder.delMetadata(metadata)); if (LOGGER.isInfoEnabled()) LOGGER.info(encoder.toString()); final Element el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.DIMENSIONINFO); assertNull(el);/*from w ww. ja v a2s . c om*/ if (el == null) LOGGER.info("REMOVED"); }
From source file:com.feilong.core.lang.NumberUtil.java
/** * ?? ??? 0.0,0.5,1.0,1.5,2.0,2.5....//from w w w . j a va 2s . c o m * * <p> * * </p> * * @param value * * @return <code>value</code> null, {@link NullPointerException} */ public static String toPointFive(Number value) { Validate.notNull(value, "value can't be null/empty!"); long avgRankLong = Math.round(Double.parseDouble(value.toString()) * 2); BigDecimal avgBigDecimal = BigDecimal.valueOf((double) (avgRankLong) / 2); return setScale(avgBigDecimal, 1).toString(); }
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 w ww . j a v a 2 s. com*/ 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.formulaone.controller.merchant.MerchantControllerTest.java
private MerchantRequest createMerchant() throws Exception { // CompanyDetails CompanyRequest company = new CompanyRequest(); company.setName("TamTam ltd"); company.setPhone("14501234123"); AddressRequest addr = new AddressRequest(); addr.setAddress("123 rue Alphonse Daudet"); addr.setCity("Laval"); addr.setState("NE"); addr.setZipCode("H6Y 1R5"); addr.setCountry("US"); company.setAddress(addr);/*from w ww.j a v a2 s. c o m*/ // build OwnerShip details OwnershipDetailsRequest details = new OwnershipDetailsRequest(); details.setDob(DateTime.now()); details.setDriverlicense("A123456789876"); details.setFirstName("Paul"); details.setLastName("Jackson"); details.setMiddleName("william"); details.setPosition("taxi driver"); details.setSsn("221-09-9307"); details.setTaxiId("taxi123458"); // bank details BankingDetailsRequest bankingDetails = new BankingDetailsRequest(); bankingDetails.setBankAccountNumber("1234567"); bankingDetails.setRoutingNumber("12345123"); // General GeneralRequest general = new GeneralRequest(); general.setAnnualProcessing("annualProcessing"); general.setCountryOfIncorporation("CA"); general.setDescriptor("Descriptor 1234567891234567891234567"); general.setPhoneNumber("1514333444"); general.setWebsite("http://www.myComany.com"); general.setBusinessType("online stuff"); MerchantRequest request = new MerchantRequest("testName", "testname@hotmail.com", "legal name llc", "describe the business", BigDecimal.valueOf(13576.23), company, details, bankingDetails, general); request.setMid(1000l); return request; }