List of usage examples for java.math BigDecimal ROUND_UP
int ROUND_UP
To view the source code for java.math BigDecimal ROUND_UP.
Click Source Link
From source file:org.runnerup.export.format.RunKeeper.java
public static ActivityEntity parseToActivity(JSONObject response, double unitMeters) throws JSONException { ActivityEntity newActivity = new ActivityEntity(); newActivity.setSport(RunKeeperSynchronizer.runkeeper2sportMap.get(response.getString("type")).getDbValue()); if (response.has("notes")) { newActivity.setComment(response.getString("notes")); }// w w w.jav a 2 s .c om newActivity.setTime((long) Float.parseFloat(response.getString("duration"))); newActivity.setDistance(Float.parseFloat(response.getString("total_distance"))); String startTime = response.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { newActivity.setStartTime(format.parse(startTime)); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } List<LapEntity> laps = new ArrayList<LapEntity>(); List<LocationEntity> locations = new ArrayList<LocationEntity>(); JSONArray distance = response.getJSONArray("distance"); JSONArray path = response.getJSONArray("path"); JSONArray hr = response.getJSONArray("heart_rate"); SortedMap<Long, HashMap<String, String>> pointsValueMap = createPointsMap(distance, path, hr); Iterator<Map.Entry<Long, HashMap<String, String>>> points = pointsValueMap.entrySet().iterator(); //lap hr int maxHr = 0; int sumHr = 0; int count = 0; //point speed long time = 0; float meters = 0.0f; //activity hr int maxHrOverall = 0; int sumHrOverall = 0; int countOverall = 0; while (points.hasNext()) { Map.Entry<Long, HashMap<String, String>> timePoint = points.next(); HashMap<String, String> values = timePoint.getValue(); LocationEntity lv = new LocationEntity(); lv.setActivityId(newActivity.getId()); lv.setTime(TimeUnit.SECONDS.toMillis(newActivity.getStartTime()) + timePoint.getKey()); String dist = values.get("distance"); if (dist == null) { continue; } String lat = values.get("latitude"); String lon = values.get("longitude"); String alt = values.get("altitude"); String heart = values.get("heart_rate"); String type = values.get("type"); if (lat == null || lon == null) { continue; } else { lv.setLatitude(Double.valueOf(lat)); lv.setLongitude(Double.valueOf(lon)); } if (alt != null) { lv.setAltitude(Double.valueOf(alt)); } if (pointsValueMap.firstKey().equals(timePoint.getKey())) { lv.setType(DB.LOCATION.TYPE_START); } else if (!points.hasNext()) { lv.setType(DB.LOCATION.TYPE_END); } else if (type != null) { lv.setType(RunKeeperSynchronizer.POINT_TYPE.get(type)); } // lap and activity max and avg hr if (heart != null) { lv.setHr(Integer.valueOf(heart)); maxHr = Math.max(maxHr, lv.getHr()); maxHrOverall = Math.max(maxHrOverall, lv.getHr()); sumHr += lv.getHr(); sumHrOverall += lv.getHr(); count++; countOverall++; } meters = Float.valueOf(dist) - meters; time = timePoint.getKey() - time; if (time > 0) { float speed = meters / (float) TimeUnit.MILLISECONDS.toSeconds(time); BigDecimal s = new BigDecimal(speed); s = s.setScale(2, BigDecimal.ROUND_UP); lv.setSpeed(s.floatValue()); } // create lap if distance greater than configured lap distance if (Float.valueOf(dist) >= unitMeters * laps.size()) { LapEntity newLap = new LapEntity(); newLap.setLap(laps.size()); newLap.setDistance(Float.valueOf(dist)); newLap.setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey())); newLap.setActivityId(newActivity.getId()); laps.add(newLap); // update previous lap with duration and distance if (laps.size() > 1) { LapEntity previousLap = laps.get(laps.size() - 2); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap.setTime( (int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } maxHr = 0; sumHr = 0; count = 0; } } // update last lap with duration and distance if (!points.hasNext()) { LapEntity previousLap = laps.get(laps.size() - 1); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap .setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } } lv.setLap(laps.size() - 1); locations.add(lv); } // calculate avg and max hr // update the activity newActivity.setMaxHr(maxHrOverall); if (countOverall > 0) { newActivity.setAvgHr(sumHrOverall / countOverall); } newActivity.putPoints(locations); newActivity.putLaps(laps); return newActivity; }
From source file:org.openhab.binding.nikobus.internal.config.ModuleChannelGroup.java
/** * Convert a 0-FF scale value to a percent type. *//* ww w . j a v a 2 s . co m*/ private PercentType getPercentTypeFromByteString(String byteValue) { long value = Long.parseLong(byteValue, 16); return new PercentType(BigDecimal.valueOf(value).multiply(BigDecimal.valueOf(100)) .divide(BigDecimal.valueOf(255), 0, BigDecimal.ROUND_UP).intValue()); }
From source file:org.egov.restapi.service.BudgetCheckService.java
public BigDecimal getAllocatedBudget(final BudgetCheck budgetCheck) { BigDecimal budgetAmountForYear, planningPercentForYear; final Scheme scheme = schemeService.findByCode(budgetCheck.getSchemeCode()); final SubScheme subScheme = subSchemeService.findByCode(budgetCheck.getSubSchemeCode()); final List<BudgetGroup> budgetheadid = new ArrayList<>(); budgetheadid.add(budgetGroupService.getBudgetGroupByName(budgetCheck.getBudgetHeadName())); Map<String, Object> paramMap = new HashMap<String, Object>(); // prepare paramMap paramMap.put(Constants.DEPTID,/*www. j av a2 s. c om*/ departmentService.getDepartmentByCode(budgetCheck.getDepartmentCode()).getId()); paramMap.put(Constants.FUNCTIONID, functionService.findByCode(budgetCheck.getFunctionCode()).getId()); paramMap.put(Constants.FUNCTIONARYID, null); paramMap.put(Constants.SCHEMEID, scheme == null ? null : Integer.parseInt(scheme.getId().toString())); paramMap.put(Constants.SUBSCHEMEID, subScheme == null ? null : Integer.parseInt(subScheme.getId().toString())); paramMap.put(Constants.FUNDID, Integer.parseInt(fundService.findByCode(budgetCheck.getFundCode()).getId().toString())); paramMap.put(Constants.BOUNDARYID, null); paramMap.put("budgetheadid", budgetheadid); paramMap.put("financialyearid", financialYearHibernateDAO.getFinYearByDate(new Date()).getId()); budgetAmountForYear = budgetDetailsDAO.getBudgetedAmtForYear(paramMap); paramMap.put(Constants.DEPTID, departmentService.getDepartmentByCode(budgetCheck.getDepartmentCode()).getId().intValue()); planningPercentForYear = budgetDetailsDAO.getPlanningPercentForYear(paramMap); return ((budgetAmountForYear.multiply(planningPercentForYear)).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_UP); }
From source file:org.yes.cart.web.support.service.impl.ShippingServiceFacadeImpl.java
/** * {@inheritDoc}/*from w ww .j a v a 2 s . co m*/ */ public ProductPriceModel getCartShippingTotal(final ShoppingCart cart) { final String currency = cart.getCurrencyCode(); final BigDecimal deliveriesCount = new BigDecimal(cart.getShippingList().size()); final BigDecimal list = cart.getTotal().getDeliveryListCost(); final BigDecimal sale = cart.getTotal().getDeliveryCost(); final boolean showTax = cart.getShoppingContext().isTaxInfoEnabled(); final boolean showTaxNet = showTax && cart.getShoppingContext().isTaxInfoUseNet(); final boolean showTaxAmount = showTax && cart.getShoppingContext().isTaxInfoShowAmount(); if (showTax) { final BigDecimal costInclTax = cart.getTotal().getDeliveryCostAmount(); if (MoneyUtils.isFirstBiggerThanSecond(costInclTax, Total.ZERO)) { final BigDecimal totalTax = cart.getTotal().getDeliveryTax(); final BigDecimal net = costInclTax.subtract(totalTax); final BigDecimal gross = costInclTax; final BigDecimal totalAdjusted = showTaxNet ? net : gross; final Set<String> taxes = new TreeSet<String>(); // sorts and de-dup's final Set<BigDecimal> rates = new TreeSet<BigDecimal>(); for (final CartItem item : cart.getShippingList()) { if (StringUtils.isNotBlank(item.getTaxCode())) { taxes.add(item.getTaxCode()); } rates.add(item.getTaxRate()); } final BigDecimal taxRate; if (MoneyUtils.isFirstBiggerThanSecond(totalTax, Total.ZERO) && rates.size() > 1) { // mixed rates in cart we use average with round up so that tax is not reduced by rounding taxRate = totalTax.multiply(MoneyUtils.HUNDRED).divide(net, Constants.DEFAULT_SCALE, BigDecimal.ROUND_UP); } else { // single rate for all items, use it to prevent rounding errors taxRate = rates.iterator().next(); } final String tax = StringUtils.join(taxes, ','); final boolean exclusiveTax = costInclTax.compareTo(sale) > 0; if (MoneyUtils.isFirstBiggerThanSecond(list, sale)) { // if we have discounts final MoneyUtils.Money listMoney = MoneyUtils.getMoney(list, taxRate, !exclusiveTax); final BigDecimal listAdjusted = showTaxNet ? listMoney.getNet() : listMoney.getGross(); return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, listAdjusted, totalAdjusted, showTax, showTaxNet, showTaxAmount, tax, taxRate, exclusiveTax, totalTax); } // no discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, totalAdjusted, null, showTax, showTaxNet, showTaxAmount, tax, taxRate, exclusiveTax, totalTax); } } // standard "as is" prices if (MoneyUtils.isFirstBiggerThanSecond(list, sale)) { // if we have discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, list, sale); } // no discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, sale, null); }
From source file:org.jahia.services.search.jcr.JahiaJCRSearchProvider.java
public SearchResponse search(SearchCriteria criteria, RenderContext context) { SearchResponse response = new SearchResponse(); List<Hit<?>> results = new ArrayList<Hit<?>>(); response.setResults(results);//from ww w .jav a 2 s .co m try { JCRSessionWrapper session = ServicesRegistry.getInstance().getJCRStoreService().getSessionFactory() .getCurrentUserSession(context.getMainResource().getWorkspace(), context.getMainResource().getLocale(), context.getFallbackLocale()); Query query = buildQuery(criteria, session); final int offset = criteria.getOffset() < 0 ? 0 : (int) criteria.getOffset(); final int limit = criteria.getLimit() <= 0 ? Integer.MAX_VALUE : (int) criteria.getLimit(); response.setOffset(offset); response.setLimit(limit); int count = 0; if (query != null) { if (logger.isDebugEnabled()) { logger.debug("Executing search query [{}]", query.getStatement()); } QueryResult queryResult = query.execute(); RowIterator it = queryResult.getRows(); Set<String> languages = new HashSet<String>(); if (it.hasNext()) { if (!criteria.getLanguages().isEmpty()) { for (String languageCode : criteria.getLanguages().getValues()) { if (!StringUtils.isEmpty(languageCode)) { languages.add(languageCode); } } } else { if (session.getLocale() != null) { languages.add(session.getLocale().toString()); } } } Set<String> usageFilterSites = !criteria.getSites().isEmpty() && !criteria.getSites().getValue().equals("-all-") && !criteria.getSitesForReferences().isEmpty() ? Sets.newHashSet(criteria.getSites().getValues()) : null; Set<String> addedNodes = new HashSet<String>(); Map<String, JCRNodeHit> addedHits = new HashMap<String, JCRNodeHit>(); List<JCRNodeHit> hitsToAdd = new ArrayList<JCRNodeHit>(); final int requiredHits = limit + offset; boolean displayableNodeCompat = Boolean.valueOf( SettingsBean.getInstance().getPropertiesFile().getProperty("search.displayableNodeCompat")); while (it.hasNext()) { count++; Row row = it.nextRow(); try { JCRNodeWrapper node = (JCRNodeWrapper) row.getNode(); if (node != null && (node.isNodeType(Constants.JAHIANT_TRANSLATION) || Constants.JCR_CONTENT.equals(node.getName()))) { node = node.getParent(); } if (node != null && node.isNodeType("jnt:vanityUrl")) { node = node.getParent().getParent(); } if (node != null && addedNodes.add(node.getIdentifier())) { boolean skipNode = isNodeToSkip(node, criteria, languages); JCRNodeHit hit = !skipNode ? buildHit(row, node, context, usageFilterSites) : null; if (!skipNode && !displayableNodeCompat) { //check if node is invisible (or don't have a displayable parent or reference) skipNode = hit.getDisplayableNode() == null; } if (!skipNode && usageFilterSites != null && !usageFilterSites.contains(node.getResolveSite().getName())) { skipNode = hit.getUsages().isEmpty(); } if (!skipNode) { hitsToAdd.add(hit); if (hitsToAdd.size() + addedHits.size() >= requiredHits) { SearchServiceImpl.executeURLModificationRules(hitsToAdd, context); addHitsToResults(hitsToAdd, results, addedHits, offset); hitsToAdd.clear(); if (addedHits.size() >= requiredHits) { response.setHasMore(true); if (it.getSize() > 0) { int approxCount = ((int) it.getSize() * addedHits.size() / count); approxCount = (int) Math.ceil(MathUtils.round(approxCount, approxCount < 1000 ? -1 : (approxCount < 10000 ? -2 : -3), BigDecimal.ROUND_UP)); response.setApproxCount(approxCount); } return response; } } } } } catch (ItemNotFoundException e) { if (logger.isDebugEnabled()) { logger.debug("Found node is not visible or published: " + row.getPath(), e); } } catch (PathNotFoundException e) { if (logger.isDebugEnabled()) { logger.debug("Found node is not visible or published: " + row.getPath(), e); } } catch (Exception e) { logger.warn("Error resolving search hit", e); } } if (hitsToAdd.size() > 0) { SearchServiceImpl.executeURLModificationRules(hitsToAdd, context); addHitsToResults(hitsToAdd, results, addedHits, offset); } } } catch (RepositoryException e) { if (e.getMessage() != null && e.getMessage().contains(ParseException.class.getName())) { logger.warn(e.getMessage()); if (logger.isDebugEnabled()) { logger.debug(e.getMessage(), e); } } else { logger.error("Error while trying to perform a search", e); } } catch (Exception e) { logger.error("Error while trying to perform a search", e); } if (logger.isDebugEnabled()) { logger.debug("Search query has {} results", results.size()); } return response; }
From source file:org.runnerup.export.RunKeeperSynchronizer.java
private String parseForNext(JSONObject resp, List<SyncActivityItem> items) throws JSONException { if (resp.has("items")) { JSONArray activities = resp.getJSONArray("items"); for (int i = 0; i < activities.length(); i++) { JSONObject item = activities.getJSONObject(i); SyncActivityItem ai = new SyncActivityItem(); String startTime = item.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { ai.setStartTime(TimeUnit.MILLISECONDS.toSeconds(format.parse(startTime).getTime())); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; }/*from w w w .j a v a2s . co m*/ Float time = Float.parseFloat(item.getString("duration")); ai.setDuration(time.longValue()); BigDecimal dist = new BigDecimal(Float.parseFloat(item.getString("total_distance"))); dist = dist.setScale(2, BigDecimal.ROUND_UP); ai.setDistance(dist.floatValue()); ai.setURI(REST_URL + item.getString("uri")); ai.setId((long) items.size()); String sport = item.getString("type"); if (runkeeper2sportMap.containsKey(sport)) { ai.setSport(runkeeper2sportMap.get(sport).getDbValue()); } else { ai.setSport(Sport.OTHER.getDbValue()); } items.add(ai); } } if (resp.has("next")) { return REST_URL + resp.getString("next"); } return null; }
From source file:org.yes.cart.web.support.service.impl.ShippingServiceFacadeImpl.java
/** * {@inheritDoc}/* w w w. j a va 2 s . c o m*/ */ public ProductPriceModel getCartShippingSupplierTotal(final ShoppingCart cart, final String supplier) { final String currency = cart.getCurrencyCode(); BigDecimal deliveriesCount = BigDecimal.ZERO; new BigDecimal(cart.getShippingList().size()); BigDecimal list = BigDecimal.ZERO; BigDecimal sale = BigDecimal.ZERO; BigDecimal taxAmount = BigDecimal.ZERO; final Set<String> taxes = new TreeSet<String>(); // sorts and de-dup's final Set<BigDecimal> rates = new TreeSet<BigDecimal>(); for (final CartItem shipping : cart.getShippingList()) { if (supplier.equals(shipping.getSupplierCode())) { deliveriesCount = deliveriesCount.add(BigDecimal.ONE); list = list.add(shipping.getListPrice().multiply(shipping.getQty()) .setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP)); sale = sale.add(shipping.getPrice().multiply(shipping.getQty()).setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP)); taxAmount = taxAmount.add(shipping.getGrossPrice().subtract(shipping.getNetPrice()) .multiply(shipping.getQty()).setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP)); if (StringUtils.isNotBlank(shipping.getTaxCode())) { taxes.add(shipping.getTaxCode()); } rates.add(shipping.getTaxRate()); } } final boolean showTax = cart.getShoppingContext().isTaxInfoEnabled(); final boolean showTaxNet = showTax && cart.getShoppingContext().isTaxInfoUseNet(); final boolean showTaxAmount = showTax && cart.getShoppingContext().isTaxInfoShowAmount(); if (showTax) { final BigDecimal costInclTax = sale; if (MoneyUtils.isFirstBiggerThanSecond(costInclTax, Total.ZERO)) { final BigDecimal totalTax = taxAmount; final BigDecimal net = costInclTax.subtract(totalTax); final BigDecimal gross = costInclTax; final BigDecimal totalAdjusted = showTaxNet ? net : gross; final BigDecimal taxRate; if (MoneyUtils.isFirstBiggerThanSecond(totalTax, Total.ZERO) && rates.size() > 1) { // mixed rates in cart we use average with round up so that tax is not reduced by rounding taxRate = totalTax.multiply(MoneyUtils.HUNDRED).divide(net, Constants.DEFAULT_SCALE, BigDecimal.ROUND_UP); } else { // single rate for all items, use it to prevent rounding errors taxRate = rates.iterator().next(); } final String tax = StringUtils.join(taxes, ','); final boolean exclusiveTax = costInclTax.compareTo(sale) > 0; if (MoneyUtils.isFirstBiggerThanSecond(list, sale)) { // if we have discounts final MoneyUtils.Money listMoney = MoneyUtils.getMoney(list, taxRate, !exclusiveTax); final BigDecimal listAdjusted = showTaxNet ? listMoney.getNet() : listMoney.getGross(); return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, listAdjusted, totalAdjusted, showTax, showTaxNet, showTaxAmount, tax, taxRate, exclusiveTax, totalTax); } // no discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, totalAdjusted, null, showTax, showTaxNet, showTaxAmount, tax, taxRate, exclusiveTax, totalTax); } } // standard "as is" prices if (MoneyUtils.isFirstBiggerThanSecond(list, sale)) { // if we have discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, list, sale); } // no discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, sale, null); }
From source file:com.salesmanager.core.module.impl.integration.shipping.FedexRequestQuotesImpl.java
public Collection<ShippingOption> getQuote(String carrier, String deliveryType, String module, Collection<PackageDetail> packages, BigDecimal orderTotal, ConfigurationResponse vo, MerchantStore store, Customer customer, Locale locale) throws Exception { // Build a RateRequest request object boolean getAllRatesFlag = true; // set to true to get the rates for // different service types RateRequest request = new RateRequest(); request.setClientDetail(createClientDetail(module, vo)); request.setWebAuthenticationDetail(createWebAuthenticationDetail(module, vo)); Collection returnColl = null; int icountry = store.getCountry(); String country = CountryUtil.getCountryIsoCodeById(icountry); IntegrationProperties props = (IntegrationProperties) vo.getConfiguration(module + "-properties"); ShippingService sservice = (ShippingService) ServiceFactory.getService(ServiceFactory.ShippingService); CoreModuleService cms = sservice.getRealTimeQuoteShippingService(country, module); /** Details on whit RT quote information to display **/ MerchantConfiguration rtdetails = vo .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES); int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME; if (rtdetails != null) { if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display // or // not // quotes try { displayQuoteDeliveryTime = Integer.parseInt(rtdetails.getConfigurationValue1()); } catch (Exception e) { log.error("Display quote is not an integer value [" + rtdetails.getConfigurationValue1() + "]"); }//from www . ja va2 s . co m } } /**/ if (cms == null) { // throw new // Exception("Central integration services not configured for " + // PaymentConstants.PAYMENT_PSIGATENAME + " and country id " + // origincountryid); log.error("CoreModuleService not configured for " + carrier + " and country id " + icountry); return null; } String host = cms.getCoreModuleServiceProdDomain(); String protocol = cms.getCoreModuleServiceProdProtocol(); String port = cms.getCoreModuleServiceProdPort(); String url = cms.getCoreModuleServiceProdEnv(); if (props.getProperties1().equals(String.valueOf(ShippingConstants.TEST_ENVIRONMENT))) { host = cms.getCoreModuleServiceDevDomain(); protocol = cms.getCoreModuleServiceDevProtocol(); port = cms.getCoreModuleServiceDevPort(); url = cms.getCoreModuleServiceDevEnv(); } // TransactionDetail transactionDetail = new TransactionDetail(); transactionDetail.setCustomerTransactionId("Shopizer salesmanager"); // The // client // will // get // the // same // value // back // in // the // response request.setTransactionDetail(transactionDetail); // VersionId versionId = new VersionId("crs", 5, 0, 0); request.setVersion(versionId); // RequestedShipment requestedShipment = new RequestedShipment(); requestedShipment.setShipTimestamp(Calendar.getInstance()); requestedShipment.setDropoffType(DropoffType.REGULAR_PICKUP); MerchantConfiguration packageServices = vo .getMerchantConfiguration(module + "-" + ShippingConstants.MODULE_SHIPPING_RT_PKG_DOM_INT); String packageOption = packageServices.getConfigurationValue(); PackagingType pType = getPackagingType(packageOption); if (deliveryType != null) { // requestedShipment.setServiceType(sType); ServiceType sType = getServiceType(deliveryType); } // if (! getAllRatesFlag) { // requestedShipment.setServiceType(ServiceType.INTERNATIONAL_PRIORITY); // requestedShipment.setServiceType(sType); requestedShipment.setPackagingType(pType); // } // Map countriesMap = (Map) RefCache .getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage())); Country c = (Country) countriesMap.get(store.getCountry()); Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage())); // Zone z = CountryUtil.getZoneCodeByName(store.getZone(), // LanguageUtil.getLanguageNumberCode(locale.getCountry())); Zone zone = (Zone) zonesMap.get(Integer.parseInt(store.getZone())); String zoneName = null; if (zone == null) { zoneName = "N/A"; } else { zoneName = zone.getZoneCode(); } /* * String originZone = zoneName; if(originZone.endsWith("QC")) { * originZone = "PQ"; } */ // origin Party shipper = new Party(); Address shipperAddress = new Address(); // Origin information shipperAddress.setStreetLines(new String[] { store.getStoreaddress() }); shipperAddress.setCity(store.getStorecity()); shipperAddress.setStateOrProvinceCode(zoneName); shipperAddress .setPostalCode(com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode())); shipperAddress.setCountryCode(c.getCountryIsoCode2()); shipper.setAddress(shipperAddress); requestedShipment.setShipper(shipper); Zone customerZone = (Zone) zonesMap.get(customer.getCustomerZoneId()); Country customerCountry = (Country) countriesMap.get(customer.getCustomerCountryId()); String customerZoneName = null; if (zone == null) { customerZoneName = "N/A"; } else { customerZoneName = customerZone.getZoneCode(); } /* * String destZone = customerZoneName; if(destZone.endsWith("QC")) { * destZone = "PQ"; } */ // destination Party recipient = new Party(); Address recipientAddress = new Address(); // Destination information recipientAddress.setStreetLines(new String[] { customer.getCustomerStreetAddress() }); recipientAddress.setCity(customer.getCustomerCity()); recipientAddress.setStateOrProvinceCode(customerZoneName); recipientAddress.setPostalCode( com.salesmanager.core.util.ShippingUtil.trimPostalCode(customer.getCustomerPostalCode())); recipientAddress.setCountryCode(customerCountry.getCountryIsoCode2()); recipient.setAddress(recipientAddress); requestedShipment.setRecipient(recipient); // Payment shippingChargesPayment = new Payment(); shippingChargesPayment.setPaymentType(PaymentType.SENDER); requestedShipment.setShippingChargesPayment(shippingChargesPayment); // build packages RequestedPackage[] rpArray = new RequestedPackage[packages.size()]; Iterator packagesIterator = packages.iterator(); int i = 0; while (packagesIterator.hasNext()) { PackageDetail detail = (PackageDetail) packagesIterator.next(); RequestedPackage rp = new RequestedPackage(); Weight w = null; if (store.getWeightunitcode().equals(Constants.LB_WEIGHT_UNIT)) { w = new Weight(WeightUnits.LB, new BigDecimal(detail.getShippingWeight())); } else { w = new Weight(WeightUnits.KG, new BigDecimal(detail.getShippingWeight())); } Dimensions d = null; BigDecimal h = new BigDecimal(detail.getShippingHeight()); h.setScale(2, BigDecimal.ROUND_UP); int ih = h.intValue(); BigDecimal sw = new BigDecimal(detail.getShippingWeight()); sw.setScale(2, BigDecimal.ROUND_UP); int isw = sw.intValue(); BigDecimal sw2 = new BigDecimal(detail.getShippingWidth()); sw2.setScale(2, BigDecimal.ROUND_UP); int isw2 = sw2.intValue(); if (store.getSeizeunitcode().equals(Constants.INCH_SIZE_UNIT)) { d = new Dimensions(new NonNegativeInteger(String.valueOf(ih)), new NonNegativeInteger(String.valueOf(isw)), new NonNegativeInteger(String.valueOf(isw2)), LinearUnits.IN); } else { d = new Dimensions(new NonNegativeInteger(String.valueOf(ih)), new NonNegativeInteger(String.valueOf(isw)), new NonNegativeInteger(String.valueOf(isw2)), LinearUnits.CM); } rp.setWeight(w); // insurance // rp.setInsuredValue(new Money(store.getCurrency(), new // BigDecimal("100.00"))); // rp.setDimensions(d); PackageSpecialServicesRequested pssr = new PackageSpecialServicesRequested(); rp.setSpecialServicesRequested(pssr); rpArray[i] = rp; i++; } requestedShipment.setRequestedPackages(rpArray); requestedShipment.setPackageCount(new NonNegativeInteger(String.valueOf(packages.size()))); requestedShipment.setRateRequestTypes(new RateRequestType[] { RateRequestType.ACCOUNT }); requestedShipment.setPackageDetail(RequestedPackageDetailType.INDIVIDUAL_PACKAGES); request.setRequestedShipment(requestedShipment); // try { // Initialize the service RateServiceLocator service; RatePortType p; // service = new RateServiceLocator(); // updateEndPoint(service); String endPointUrl = protocol + "://" + host + ":" + port + url; service.setRateServicePortEndpointAddress(endPointUrl); p = service.getRateServicePort(); // This is the call to the web service passing in a RateRequest and // returning a RateReply RateReply reply = p.getRates(request); // Service call if (isResponseOk(reply.getHighestSeverity())) { returnColl = writeServiceOutput(displayQuoteDeliveryTime, reply, module, carrier, locale, store.getCurrency()); } printNotifications(store, reply.getNotifications()); } catch (RuntimeException e) { e.printStackTrace(); log.error(e); } catch (Exception ex) { log.error(ex); } return returnColl; }
From source file:org.egov.collection.web.actions.receipts.ReceiptAction.java
@Override public void prepare() { super.prepare(); BillInfoImpl collDetails;//w w w .j a v a 2 s .c om setReceiptCreatedByCounterOperator(collectionsUtil.getLoggedInUser()); // populates model when request is from the billing system if (getCollectXML() != null && !getCollectXML().isEmpty()) { final String decodedCollectXML = decodeBillXML(); try { collDetails = BillInfoMarshaller.toObject(decodedCollectXML); final Fund fund = fundDAO.fundByCode(collDetails.getFundCode()); if (fund == null) addActionError(getText("billreceipt.improperbilldata.missingfund")); setFundName(fund.getName()); final Department dept = (Department) getPersistenceService().findByNamedQuery( CollectionConstants.QUERY_DEPARTMENT_BY_CODE, collDetails.getDepartmentCode()); if (dept == null) addActionError(getText("billreceipt.improperbilldata.missingdepartment")); final ServiceDetails service = (ServiceDetails) getPersistenceService() .findByNamedQuery(CollectionConstants.QUERY_SERVICE_BY_CODE, collDetails.getServiceCode()); setServiceName(service.getName()); setCollectionModesNotAllowed(collDetails.getCollectionModesNotAllowed()); setOverrideAccountHeads(collDetails.getOverrideAccountHeadsAllowed()); setCallbackForApportioning(collDetails.getCallbackForApportioning()); setPartPaymentAllowed(collDetails.getPartPaymentAllowed()); totalAmntToBeCollected = BigDecimal.ZERO; // populate bank account list populateBankBranchList(true); receiptHeader = collectionCommon.initialiseReceiptModelWithBillInfo(collDetails, fund, dept); totalAmntToBeCollected = totalAmntToBeCollected.add(receiptHeader.getTotalAmountToBeCollected()); for (final ReceiptDetail rDetails : receiptHeader.getReceiptDetails()) rDetails.getCramountToBePaid().setScale(CollectionConstants.AMOUNT_PRECISION_DEFAULT, BigDecimal.ROUND_UP); setReceiptDetailList(new ArrayList<ReceiptDetail>(receiptHeader.getReceiptDetails())); if (totalAmntToBeCollected.compareTo(BigDecimal.ZERO) == -1) { addActionError(getText("billreceipt.totalamountlessthanzero.error")); LOGGER.info(getText("billreceipt.totalamountlessthanzero.error")); } else setTotalAmntToBeCollected(totalAmntToBeCollected .setScale(CollectionConstants.AMOUNT_PRECISION_DEFAULT, BigDecimal.ROUND_UP)); } catch (final Exception e) { LOGGER.error(getText("billreceipt.error.improperbilldata"), e); addActionError(getText("billreceipt.error.improperbilldata")); } } addDropdownData("serviceCategoryList", serviceCategoryService.findAllByNamedQuery(CollectionConstants.QUERY_ACTIVE_SERVICE_CATEGORY)); addDropdownData("serviceList", Collections.emptyList()); if (instrumentProxyList == null) instrumentCount = 0; else instrumentCount = instrumentProxyList.size(); }
From source file:com.abiquo.api.services.cloud.VirtualApplianceService.java
private BigDecimal rounded(final int significantDigits, final BigDecimal aNumber) { return aNumber.setScale(significantDigits, BigDecimal.ROUND_UP); }