List of usage examples for java.math BigDecimal ROUND_HALF_UP
int ROUND_HALF_UP
To view the source code for java.math BigDecimal ROUND_HALF_UP.
Click Source Link
From source file:org.kalypso.model.wspm.pdb.internal.gaf.Gaf2Db.java
private BigDecimal calculateWidthFromDistance(final GafPart gafPart, final com.vividsolutions.jts.geom.Point location) { final GafPoint startPoint = gafPart.getPoints()[0]; final com.vividsolutions.jts.geom.Point startLocation = startPoint.getPoint(); if (location == null || startLocation == null) return null; final double distance = location.distance(startLocation); return new BigDecimal(distance).setScale(3, BigDecimal.ROUND_HALF_UP); }
From source file:org.kuali.kfs.gl.service.TrialBalanceServiceTest.java
private BigDecimal getBalance(List<TrialBalanceReport> trialBalanceReports, BalanceType balanceType) { BigDecimal balance = BigDecimal.ZERO.setScale(SCALE, BigDecimal.ROUND_HALF_UP); for (TrialBalanceReport trialBalanceReport : trialBalanceReports) { KualiDecimal testBalance;/*from www. j a v a 2 s . com*/ if (balanceType == BalanceType.CREDIT) { testBalance = trialBalanceReport.getCreditAmount(); } else { // balanceType == BalanceType.DEBIT testBalance = trialBalanceReport.getDebitAmount(); } if (ObjectUtils.isNotNull(testBalance)) { balance = balance.add(testBalance.bigDecimalValue().setScale(SCALE, BigDecimal.ROUND_HALF_UP)); } } //for return balance; }
From source file:com.esd.cs.audit.AuditsController.java
/** * ??// w w w . j av a 2 s . co m * * @param calculateModel * @return */ @RequestMapping(value = "/calculate", method = RequestMethod.POST) @ResponseBody public CalculateModel calculateModel(CalculateModel calculateModel) { logger.debug(calculateModel.toString()); Integer companyId = calculateModel.getCompanyId(); String year = calculateModel.getYear(); AuditParameter auditParameter = auditParameterService.getByYear(year); // ? Integer zaiZhiYuanGongZongShu = calculateModel.getZaiZhiYuanGongZongShu(); if (zaiZhiYuanGongZongShu == null) { zaiZhiYuanGongZongShu = 0; } // BigDecimal putScale = auditParameter.getPutScale(); // // =????* BigDecimal yingAnPaiCanJiRen = putScale.multiply(new BigDecimal(zaiZhiYuanGongZongShu)).setScale(2, BigDecimal.ROUND_HALF_UP); calculateModel.setYingAnPaiCanJiRen(yingAnPaiCanJiRen);// // ======================================================================================== // Integer yiLuRuCanJiRen = calculateModel.getYiLuRuCanJiRen(); // ??? List<WorkerCalculator> list = auditParameterService.getSpecialSetting(year); for (WorkerCalculator workerCalculator : list) { Integer per = workerCalculator.getPer().intValue(); Integer type = workerCalculator.getType(); Integer lvl = workerCalculator.getLvl(); Integer num = auditParameterService.getSpecialCount(companyId, year, type, lvl); logger.debug("type:{},lvl:{},per:{}", type, lvl, per); yiLuRuCanJiRen = ((yiLuRuCanJiRen - num) + (num * per)); } // Integer yuDingCanJiRen = calculateModel.getYuDingCanJiRen(); // Integer yiAnPaiCanJiRen = yiLuRuCanJiRen + yuDingCanJiRen; calculateModel.setYiAnPaiCanJiRen(yiAnPaiCanJiRen);// ; // ========================================================================================= // ?? BigDecimal averageSalary = auditParameter.getAverageSalary(); // ? // ??*() BigDecimal yingJiaoJinE = averageSalary .multiply(yingAnPaiCanJiRen.subtract(new BigDecimal(yiAnPaiCanJiRen))); if (yingJiaoJinE.signum() == 1) {// 0 calculateModel.setYingJiaoJinE(yingJiaoJinE); } else { yingJiaoJinE = Constants.ZERO; calculateModel.setYingJiaoJinE(yingJiaoJinE); } // ?? BigDecimal jianJiaoJinE = calculateModel.getJianJiaoJinE(); // ?=?-?? BigDecimal shiJiaoJinE = yingJiaoJinE.subtract(jianJiaoJinE); // ? --------? // ============================================================? List<AccountModel> qianJiaoMingXi = new ArrayList<AccountModel>(); BigDecimal qianJiao = getSectionPaid(year, companyId, qianJiaoMingXi); calculateModel.setQianJiaoMingXi(qianJiaoMingXi); // ============================================================ List<AccountModel> weiShenMingXi = new ArrayList<AccountModel>(); BigDecimal weiShen = getUnAudits(year, companyId, new BigDecimal(zaiZhiYuanGongZongShu), weiShenMingXi); calculateModel.setWeiShenMingXi(weiShenMingXi); // ============================================================= List<AccountModel> weiJiaoMingXi = new ArrayList<AccountModel>(); BigDecimal weiJiao = getUnpaid(year, companyId, weiJiaoMingXi); calculateModel.setWeiJiaoMingXi(weiJiaoMingXi); // ==================================================================? logger.debug("qianJiao:{} weiShen:{} weiJiao{}", qianJiao, weiShen, weiJiao); // ? =++ BigDecimal shangNianDuWeiJiaoBaoZhangJin = qianJiao.add(weiShen).add(weiJiao); calculateModel.setShangNianDuWeiJiaoBaoZhangJin(shangNianDuWeiJiaoBaoZhangJin); // ===================================================================================================== // ?=?-??+?+? BigDecimal real_yingJiaoJinE = shiJiaoJinE.add(shangNianDuWeiJiaoBaoZhangJin); // BigDecimal real_yingJiaoJinE = shiJiaoJinE; calculateModel.setShiJiaoJinE(real_yingJiaoJinE);// ? // ============================================================================================ // Date date = auditParameter.getAuditDelayDate(); // BigDecimal zhiNaJinBiLi = auditParameter.getAuditDelayRate(); // int zhiNanJinTianshu = CalendarUtil.getDaySub(date, new Date()); if (zhiNanJinTianshu < 0) { zhiNanJinTianshu = 0; } calculateModel.setZhiNaJinTianShu(zhiNanJinTianshu);// // BigDecimal zhiNaJin = real_yingJiaoJinE.multiply(zhiNaJinBiLi).multiply(new BigDecimal(zhiNanJinTianshu)); // ?? Boolean mian = calculateModel.getMianZhiNaJin(); if (mian) { zhiNaJin = new BigDecimal(0.00); } calculateModel.setZhiNaJin(zhiNaJin);// // =============================================================================================== // ?=?+ BigDecimal shiJiaoZongJinE = real_yingJiaoJinE.add(zhiNaJin); Boolean mianJiao = calculateModel.getMianJiao();// ??? if (mianJiao) { shiJiaoZongJinE = new BigDecimal(0.00); } calculateModel.setShiJiaoZongJinE(shiJiaoZongJinE); return calculateModel; }
From source file:org.egov.ptis.service.es.PropertyTaxElasticSearchIndexService.java
/** * Populates the consolidated demand information in CollectionIndexDetails * * @param collectionDetailsRequest/*from w w w. j av a 2 s. c o m*/ * @param collectionIndexDetails */ public void getConsolidatedDemandInfo(final CollectionDetailsRequest collectionDetailsRequest, final CollectionDetails collectionIndexDetails) { Date fromDate; Date toDate; final CFinancialYear currFinYear = cFinancialYearService.getFinancialYearByDate(new Date()); /** * For fetching total demand between the date ranges if dates are sent in the request, consider fromDate and toDate+1 , * else calculate from current year start date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), "yyyy-MM-dd"); toDate = DateUtils.getDate(collectionDetailsRequest.getToDate(), "yyyy-MM-dd"); } else { fromDate = DateUtils.startOfDay(currFinYear.getStartingDate()); toDate = new Date(); } final BigDecimal totalDemand = getTotalDemandBasedOnInputFilters(collectionDetailsRequest); final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; collectionIndexDetails.setTotalDmd(totalDemand); // Proportional Demand = (totalDemand/12)*noOfmonths final BigDecimal proportionalDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); collectionIndexDetails.setCytdDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP)); collectionIndexDetails.setTotalAssessments( collectionIndexElasticSearchService.getTotalAssessmentsCount(collectionDetailsRequest)); if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0) // performance = (current year tilldate collection * 100)/(proportional demand) collectionIndexDetails.setPerformance( collectionIndexDetails.getCytdColl().multiply(PropertyTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); // variance = ((currentYearCollection - lastYearCollection)*100)/lastYearCollection BigDecimal variation; if (collectionIndexDetails.getLytdColl().compareTo(BigDecimal.ZERO) == 0) variation = BIGDECIMAL_100; else variation = collectionIndexDetails.getCytdColl().subtract(collectionIndexDetails.getLytdColl()) .multiply(BIGDECIMAL_100) .divide(collectionIndexDetails.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP); collectionIndexDetails.setLyVar(variation); }
From source file:com.osafe.services.OsafePayPalServices.java
public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); HttpServletRequest request = (HttpServletRequest) context.get("request"); HttpServletResponse response = (HttpServletResponse) context.get("response"); Map<String, Object> paramMap = UtilHttp.getParameterMap(request); String token = (String) paramMap.get("TOKEN"); WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token)); ShoppingCart cart = null;//from w w w .j a v a2s. c o m if (weakCart != null) { cart = weakCart.get(); } if (cart == null) { Debug.logError("Could locate the ShoppingCart for token " + token, module); return ServiceUtil.returnSuccess(); } // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and // then delete once we're done, now is not the time to worry about updating everything String contactMechId = null; Map<String, Object> inMap = FastMap.newInstance(); inMap.put("address1", paramMap.get("SHIPTOSTREET")); inMap.put("address2", paramMap.get("SHIPTOSTREET2")); inMap.put("city", paramMap.get("SHIPTOCITY")); String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY"); String countryGeoId = OsafePayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator); if (countryGeoId == null) { return ServiceUtil.returnSuccess(); } inMap.put("countryGeoId", countryGeoId); inMap.put("stateProvinceGeoId", parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator)); inMap.put("postalCode", paramMap.get("SHIPTOZIP")); try { GenericValue userLogin = delegator.findOne("UserLogin", true, UtilMisc.toMap("userLoginId", "system")); inMap.put("userLogin", userLogin); } catch (GenericEntityException e) { Debug.logError(e, module); } boolean beganTransaction = false; Transaction parentTransaction = null; try { parentTransaction = TransactionUtil.suspend(); beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException e1) { Debug.logError(e1, module); } try { Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap); contactMechId = (String) outMap.get("contactMechId"); } catch (GenericServiceException e) { Debug.logError(e.getMessage(), module); return ServiceUtil.returnSuccess(); } try { TransactionUtil.commit(beganTransaction); if (parentTransaction != null) TransactionUtil.resume(parentTransaction); } catch (GenericTransactionException e) { Debug.logError(e, module); } // clone the cart so we can modify it temporarily CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart); String oldShipAddress = cart.getShippingContactMechId(); coh.setCheckOutShippingAddress(contactMechId); ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0); int line = 0; NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "CallbackResponse"); for (GenericValue shipMethod : estWrapper.getShippingMethods()) { BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod); //Check that we have a valid estimate (allowing zero value estimates for now) if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) { continue; } cart.setShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId")); cart.setCarrierPartyId(shipMethod.getString("partyId")); try { coh.calcAndAddTax(); } catch (GeneralException e) { Debug.logError(e, module); continue; } String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description"); encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel); encoder.add("L_SHIPPINGOPTIONAMOUNT" + line, estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); // Just make this first one default for now encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false"); encoder.add("L_TAXAMT" + line, cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); line++; } String responseMsg = null; try { responseMsg = encoder.encode(); } catch (PayPalException e) { Debug.logError(e, module); } if (responseMsg != null) { try { response.setContentLength(responseMsg.getBytes("UTF-8").length); } catch (UnsupportedEncodingException e) { Debug.logError(e, module); } try { Writer writer = response.getWriter(); writer.write(responseMsg); writer.close(); } catch (IOException e) { Debug.logError(e, module); } } // Remove the temporary ship address try { GenericValue postalAddress = delegator.findOne("PostalAddress", false, UtilMisc.toMap("contactMechId", contactMechId)); postalAddress.remove(); GenericValue contactMech = delegator.findOne("ContactMech", false, UtilMisc.toMap("contactMechId", contactMechId)); contactMech.remove(); } catch (GenericEntityException e) { Debug.logError(e, module); } coh.setCheckOutShippingAddress(oldShipAddress); return ServiceUtil.returnSuccess(); }
From source file:com.tagaugmentedreality.NearByTagsList.java
public void prepareTagsList(String latitude, String longitude) { tagListView = (ListView) view.findViewById(R.id.tagListView); // tagListView.setVisibility(View.GONE); /*/*from w ww .j a v a2 s . c o m*/ * I am building the tags list */ for (int i = 0; i < TagListCache.getTagsList().size(); i++) { TagListCache.getTagsList().get(i).destroyTag(); TagListCache.getTagsList().remove(i); } // end for TagListCache.getTagsList().clear(); TagCache tag; OpenGLModelCache openGLModel; Location tagLocation = new Location(" "); Location deviceLocation = new Location(" "); deviceLocation.setLatitude(Utilities.LATITUDE); deviceLocation.setLongitude(Utilities.LONGITUDE); Float bearing = 0.0f; Float distance = 0.0f; BigDecimal bearingRounded; /* * TagCache(String id, OpenGLModelCache openGLModel, String title, * String comment, Double latitude, Double longitude, String * tagImageLink, String accuracy, String distance, Float direction, * String firstName, String lastName, String userFacebookId, String * city, String province, String country, boolean grouped ) */ // tag1 tag = new TagCache("1", null, "Tag1", "Tag1 is here.", Double.parseDouble(latitude), Double.parseDouble(longitude), "", "10", "10", 0.0f, "Lahore", "Punjab", "Pakistan", false); openGLModel = new OpenGLModelCache(); openGLModel.resetVector(); /** * I am getting the bearing of the tag with the device right here, by * using the latitude and longitude of both the tag and the device. Then * i am saving the value as the tag's heading. */ tagLocation.setLatitude(Double.parseDouble("31.459379")); tagLocation.setLongitude(Double.parseDouble("74.368984")); distance = deviceLocation.distanceTo(tagLocation); bearing = deviceLocation.bearingTo(tagLocation); if (bearing < 0) { bearing = (-1) * bearing; bearing = 180 + (180 - bearing); } // end if bearingRounded = new BigDecimal(bearing).setScale(0, BigDecimal.ROUND_HALF_UP); bearing = Float.parseFloat(bearingRounded.toString()); Log.e(Utilities.TAG, "bearing: " + bearing.toString()); openGLModel.setHeading(bearing);// dataObject.getString("direction"))); tag.setDirection(bearing); tag.setOpenGLModel(openGLModel); tag.setDistance(distance.toString()); TagListCache.getTagsList().add(tag); // tag2 tag = new TagCache("2", null, "Tag2", "Tag2 is here.", Double.parseDouble(latitude), Double.parseDouble(longitude), "", "10", "10", 0.0f, "Lahore", "Punjab", "Pakistan", false); openGLModel = new OpenGLModelCache(); openGLModel.resetVector(); /** * I am getting the bearing of the tag with the device right here, by * using the latitude and longitude of both the tag and the device. Then * i am saving the value as the tag's heading. */ tagLocation.setLatitude(Double.parseDouble("31.459379")); tagLocation.setLongitude(Double.parseDouble("74.368984")); distance = deviceLocation.distanceTo(tagLocation); bearing = deviceLocation.bearingTo(tagLocation); if (bearing < 0) { bearing = (-1) * bearing; bearing = 180 + (180 - bearing); } // end if bearingRounded = new BigDecimal(bearing).setScale(0, BigDecimal.ROUND_HALF_UP); bearing = Float.parseFloat(bearingRounded.toString()); Log.e(Utilities.TAG, "bearing: " + bearing.toString()); openGLModel.setHeading(bearing);// dataObject.getString("direction"))); tag.setDirection(bearing); tag.setOpenGLModel(openGLModel); tag.setDistance(distance.toString()); TagListCache.getTagsList().add(tag); // tag3 tag = new TagCache("3", null, "Tag3", "Tag3 is here.", Double.parseDouble(latitude), Double.parseDouble(longitude), "", "10", "10", 0.0f, "Lahore", "Punjab", "Pakistan", false); openGLModel = new OpenGLModelCache(); openGLModel.resetVector(); /** * I am getting the bearing of the tag with the device right here, by * using the latitude and longitude of both the tag and the device. Then * i am saving the value as the tag's heading. */ tagLocation.setLatitude(Double.parseDouble("31.458804")); tagLocation.setLongitude(Double.parseDouble("74.368874")); distance = deviceLocation.distanceTo(tagLocation); bearing = deviceLocation.bearingTo(tagLocation); if (bearing < 0) { bearing = (-1) * bearing; bearing = 180 + (180 - bearing); } // end if bearingRounded = new BigDecimal(bearing).setScale(0, BigDecimal.ROUND_HALF_UP); bearing = Float.parseFloat(bearingRounded.toString()); Log.e(Utilities.TAG, "bearing: " + bearing.toString()); openGLModel.setHeading(bearing);// dataObject.getString("direction"))); tag.setDirection(bearing); tag.setOpenGLModel(openGLModel); tag.setDistance(distance.toString()); TagListCache.getTagsList().add(tag); // tag4 tag = new TagCache("4", null, "Tag4", "Tag4 is here.", Double.parseDouble(latitude), Double.parseDouble(longitude), "", "10", "10", 0.0f, "Lahore", "Punjab", "Pakistan", false); openGLModel = new OpenGLModelCache(); openGLModel.resetVector(); /** * I am getting the bearing of the tag with the device right here, by * using the latitude and longitude of both the tag and the device. Then * i am saving the value as the tag's heading. */ tagLocation.setLatitude(Double.parseDouble("31.458651")); tagLocation.setLongitude(Double.parseDouble("74.369171")); distance = deviceLocation.distanceTo(tagLocation); bearing = deviceLocation.bearingTo(tagLocation); if (bearing < 0) { bearing = (-1) * bearing; bearing = 180 + (180 - bearing); } // end if bearingRounded = new BigDecimal(bearing).setScale(0, BigDecimal.ROUND_HALF_UP); bearing = Float.parseFloat(bearingRounded.toString()); Log.e(Utilities.TAG, "bearing: " + bearing.toString()); openGLModel.setHeading(bearing);// dataObject.getString("direction"))); tag.setDirection(bearing); tag.setOpenGLModel(openGLModel); tag.setDistance(distance.toString()); TagListCache.getTagsList().add(tag); /* * I am building the combined tags list to be used by the Browser */ temporaryList.clear(); CombinedTagListCache.getCombinedList().clear(); CombinedTagCache combinedTag; int counter = 1; for (int i = 0; i < TagListCache.getTagsList().size(); ++i) { temporaryList.add(TagListCache.getTagsList().get(i).getTitle()); /** * I am creating the combined tags list on the basis that each tag * in the group is separated (direction of each tag is away from * each other by the value given by * Utilities.combinedDirectionCriteria degrees) by * Utilities.combinedDirectionCriteria degrees. I am grouping * together tags because there is limited real estate in the * Augmented Reality View Screen. */ combinedTag = new CombinedTagCache(); if (!TagListCache.getTagsList().get(i).isGrouped()) { TagListCache.getTagsList().get(i).setGrouped(true); combinedTag.setId(((Integer) counter).toString()); combinedTag.getTagList().add(TagListCache.getTagsList().get(i)); combinedTag.setOpenGLModel(TagListCache.getTagsList().get(i).getOpenGLModel()); combinedTag.setDirection(TagListCache.getTagsList().get(i).getDirection()); combinedTag.setLatitude(TagListCache.getTagsList().get(i).getLatitude()); combinedTag.setLongitude(TagListCache.getTagsList().get(i).getLongitude()); CombinedTagListCache.getCombinedList().add(combinedTag); for (int j = 0; j < TagListCache.getTagsList().size(); j++) { if (!TagListCache.getTagsList().get(j).isGrouped()) { if (Math.abs(TagListCache.getTagsList().get(i).getDirection() - TagListCache.getTagsList() .get(j).getDirection()) < Utilities.COMBINED_DIRECTION_CRITERIA) { combinedTag.getTagList().add(TagListCache.getTagsList().get(j)); TagListCache.getTagsList().get(j).setGrouped(true); } // end if } // end if } // end for counter++; } // end if } // end for Log.e("combined tags size: ", "" + CombinedTagListCache.getCombinedList().size()); for (int i = 0; i < CombinedTagListCache.getCombinedList().size(); i++) { Log.e("combined: ", "" + CombinedTagListCache.getCombinedList().get(i).getId()); for (int j = 0; j < CombinedTagListCache.getCombinedList().get(i).getTagList().size(); j++) { Log.e("combined tag: ", "" + CombinedTagListCache.getCombinedList().get(i).getTagList().get(j).getDirection()); } // end for } // end for adapter.notifyDataSetChanged(); // tagListView.setVisibility(View.VISIBLE); if (null != Lists.getActionProgressBar()) { Lists.getActionProgressBar().collapseActionView(); Lists.getActionProgressBar().setActionView(null); } // end if }
From source file:com.salesmanager.core.module.impl.integration.shipping.UPSQuotesImpl.java
public Collection<ShippingOption> getShippingQuote(ConfigurationResponse config, BigDecimal orderTotal, Collection<PackageDetail> packages, Customer customer, MerchantStore store, Locale locale) { CoreModuleService cis = null;//from w w w . jav a 2s . co m StringBuffer xmlbuffer = new StringBuffer(); BufferedReader reader = null; PostMethod httppost = null; try { CommonService cservice = (CommonService) ServiceFactory.getService(ServiceFactory.CommonService); String countrycode = CountryUtil.getCountryIsoCodeById(store.getCountry()); cis = cservice.getModule(countrycode, "upsxml"); if (cis == null) { log.error("Can't retreive an integration service [countryid " + store.getCountry() + " ups subtype 1]"); // throw new // Exception("UPS getQuote Can't retreive an integration service"); } MerchantService service = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService); ConfigurationRequest request_prefs = new ConfigurationRequest(store.getMerchantId(), ShippingConstants.MODULE_SHIPPING_RT_PKG_DOM_INT); ConfigurationResponse vo_prefs = service.getConfiguration(request_prefs); String pack = (String) vo_prefs.getConfiguration("package-upsxml"); if (pack == null) { log.debug("Will assign packaging type 02 to UPS shipping for merchantid " + store.getMerchantId()); pack = "02"; } ConfigurationRequest request = new ConfigurationRequest(store.getMerchantId(), ShippingConstants.MODULE_SHIPPING_RT_CRED); ConfigurationResponse vo = service.getConfiguration(request); if (vo == null) { throw new Exception("ConfigurationVO is null upsxml"); } String xmlhead = getHeader(store.getMerchantId(), vo); String weightCode = store.getWeightunitcode(); String measureCode = store.getSeizeunitcode(); if (weightCode.equals("KG")) { weightCode = "KGS"; } else { weightCode = "LBS"; } String xml = "<?xml version=\"1.0\"?><RatingServiceSelectionRequest><Request><TransactionReference><CustomerContext>SalesManager Data</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>Rate</RequestAction><RequestOption>Shop</RequestOption></Request>"; StringBuffer xmldatabuffer = new StringBuffer(); /** * <Shipment> * * <Shipper> <Address> <City></City> * <StateProvinceCode>QC</StateProvinceCode> * <CountryCode>CA</CountryCode> <PostalCode></PostalCode> * </Address> </Shipper> * * <ShipTo> <Address> <City>Redwood Shores</City> * <StateProvinceCode>CA</StateProvinceCode> * <CountryCode>US</CountryCode> <PostalCode></PostalCode> * <ResidentialAddressIndicator/> </Address> </ShipTo> * * <Package> <PackagingType> <Code>21</Code> </PackagingType> * <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code> * </UnitOfMeasurement> <Weight>1.1</Weight> </PackageWeight> * <PackageServiceOptions> <InsuredValue> * <CurrencyCode>CAD</CurrencyCode> * <MonetaryValue>100</MonetaryValue> </InsuredValue> * </PackageServiceOptions> </Package> * * * </Shipment> * * <CustomerClassification> <Code>03</Code> * </CustomerClassification> </RatingServiceSelectionRequest> * **/ Map countriesMap = (Map) RefCache .getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage())); Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage())); Country storeCountry = (Country) countriesMap.get(store.getCountry()); Country customerCountry = (Country) countriesMap.get(customer.getCustomerCountryId()); int sZone = -1; try { sZone = Integer.parseInt(store.getZone()); } catch (Exception e) { // TODO: handle exception } Zone storeZone = (Zone) zonesMap.get(sZone); Zone customerZone = (Zone) zonesMap.get(customer.getCustomerZoneId()); xmldatabuffer.append("<PickupType><Code>03</Code></PickupType>"); // xmldatabuffer.append("<Description>Daily Pickup</Description>"); xmldatabuffer.append("<Shipment><Shipper>"); xmldatabuffer.append("<Address>"); xmldatabuffer.append("<City>"); xmldatabuffer.append(store.getStorecity()); xmldatabuffer.append("</City>"); // if(!StringUtils.isBlank(store.getStorestateprovince())) { if (storeZone != null) { xmldatabuffer.append("<StateProvinceCode>"); xmldatabuffer.append(storeZone.getZoneCode());// zone code xmldatabuffer.append("</StateProvinceCode>"); } xmldatabuffer.append("<CountryCode>"); xmldatabuffer.append(storeCountry.getCountryIsoCode2()); xmldatabuffer.append("</CountryCode>"); xmldatabuffer.append("<PostalCode>"); xmldatabuffer .append(com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode())); xmldatabuffer.append("</PostalCode></Address></Shipper>"); // ship to xmldatabuffer.append("<ShipTo>"); xmldatabuffer.append("<Address>"); xmldatabuffer.append("<City>"); xmldatabuffer.append(customer.getCustomerCity()); xmldatabuffer.append("</City>"); // if(!StringUtils.isBlank(customer.getCustomerState())) { if (customerZone != null) { xmldatabuffer.append("<StateProvinceCode>"); xmldatabuffer.append(customerZone.getZoneCode());// zone code xmldatabuffer.append("</StateProvinceCode>"); } xmldatabuffer.append("<CountryCode>"); xmldatabuffer.append(customerCountry.getCountryIsoCode2()); xmldatabuffer.append("</CountryCode>"); xmldatabuffer.append("<PostalCode>"); xmldatabuffer.append( com.salesmanager.core.util.ShippingUtil.trimPostalCode(customer.getCustomerPostalCode())); xmldatabuffer.append("</PostalCode></Address></ShipTo>"); // xmldatabuffer.append("<Service><Code>11</Code></Service>"); Iterator packagesIterator = packages.iterator(); while (packagesIterator.hasNext()) { PackageDetail detail = (PackageDetail) packagesIterator.next(); xmldatabuffer.append("<Package>"); xmldatabuffer.append("<PackagingType>"); xmldatabuffer.append("<Code>"); xmldatabuffer.append(pack); xmldatabuffer.append("</Code>"); xmldatabuffer.append("</PackagingType>"); // weight xmldatabuffer.append("<PackageWeight>"); xmldatabuffer.append("<UnitOfMeasurement>"); xmldatabuffer.append("<Code>"); xmldatabuffer.append(weightCode); xmldatabuffer.append("</Code>"); xmldatabuffer.append("</UnitOfMeasurement>"); xmldatabuffer.append("<Weight>"); xmldatabuffer .append(new BigDecimal(detail.getShippingWeight()).setScale(1, BigDecimal.ROUND_HALF_UP)); xmldatabuffer.append("</Weight>"); xmldatabuffer.append("</PackageWeight>"); // dimension xmldatabuffer.append("<Dimensions>"); xmldatabuffer.append("<UnitOfMeasurement>"); xmldatabuffer.append("<Code>"); xmldatabuffer.append(measureCode); xmldatabuffer.append("</Code>"); xmldatabuffer.append("</UnitOfMeasurement>"); xmldatabuffer.append("<Length>"); xmldatabuffer .append(new BigDecimal(detail.getShippingLength()).setScale(2, BigDecimal.ROUND_HALF_UP)); xmldatabuffer.append("</Length>"); xmldatabuffer.append("<Width>"); xmldatabuffer .append(new BigDecimal(detail.getShippingWidth()).setScale(2, BigDecimal.ROUND_HALF_UP)); xmldatabuffer.append("</Width>"); xmldatabuffer.append("<Height>"); xmldatabuffer .append(new BigDecimal(detail.getShippingHeight()).setScale(2, BigDecimal.ROUND_HALF_UP)); xmldatabuffer.append("</Height>"); xmldatabuffer.append("</Dimensions>"); xmldatabuffer.append("</Package>"); } xmldatabuffer.append("</Shipment>"); xmldatabuffer.append("</RatingServiceSelectionRequest>"); xmlbuffer.append(xmlhead).append(xml).append(xmldatabuffer.toString()); log.debug("UPS QUOTE REQUEST " + xmlbuffer.toString()); String data = ""; IntegrationKeys keys = (IntegrationKeys) config.getConfiguration("upsxml-keys"); IntegrationProperties props = (IntegrationProperties) config.getConfiguration("upsxml-properties"); String host = cis.getCoreModuleServiceProdDomain(); String protocol = cis.getCoreModuleServiceProdProtocol(); String port = cis.getCoreModuleServiceProdPort(); String uri = cis.getCoreModuleServiceProdEnv(); if (props.getProperties1().equals(String.valueOf(ShippingConstants.TEST_ENVIRONMENT))) { host = cis.getCoreModuleServiceDevDomain(); protocol = cis.getCoreModuleServiceDevProtocol(); port = cis.getCoreModuleServiceDevPort(); uri = cis.getCoreModuleServiceDevEnv(); } HttpClient client = new HttpClient(); httppost = new PostMethod(protocol + "://" + host + ":" + port + uri); RequestEntity entity = new StringRequestEntity(xmlbuffer.toString(), "text/plain", "UTF-8"); httppost.setRequestEntity(entity); int result = client.executeMethod(httppost); if (result != 200) { log.error("Communication Error with ups quote " + result + " " + protocol + "://" + host + ":" + port + uri); throw new Exception("UPS quote communication error " + result); } data = httppost.getResponseBodyAsString(); log.debug("ups quote response " + data); UPSParsedElements parsed = new UPSParsedElements(); Digester digester = new Digester(); digester.push(parsed); digester.addCallMethod("RatingServiceSelectionResponse/Response/Error", "setErrorCode", 0); digester.addCallMethod("RatingServiceSelectionResponse/Response/ErrorDescriprion", "setError", 0); digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusCode", "setStatusCode", 0); digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusDescription", "setStatusMessage", 0); digester.addCallMethod("RatingServiceSelectionResponse/Response/Error/ErrorDescription", "setError", 0); digester.addObjectCreate("RatingServiceSelectionResponse/RatedShipment", com.salesmanager.core.entity.shipping.ShippingOption.class); // digester.addSetProperties( // "RatingServiceSelectionResponse/RatedShipment", "sequence", // "optionId" ); digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionId", 0); digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/TotalCharges/MonetaryValue", "setOptionPriceText", 0); digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/TotalCharges/CurrencyCode", "setCurrency", 0); digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionCode", 0); digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/GuaranteedDaysToDelivery", "setEstimatedNumberOfDays", 0); digester.addSetNext("RatingServiceSelectionResponse/RatedShipment", "addOption"); // <?xml // version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager // Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The // XML document is well formed but the document is not // valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse> Reader xmlreader = new StringReader(data); digester.parse(xmlreader); if (!StringUtils.isBlank(parsed.getErrorCode())) { log.error( "Can't process UPS statusCode=" + parsed.getErrorCode() + " message= " + parsed.getError()); return null; } if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) { LogMerchantUtil.log(store.getMerchantId(), "Can't process UPS statusCode=" + parsed.getStatusCode() + " message= " + parsed.getError()); log.error("Can't process UPS statusCode=" + parsed.getStatusCode() + " message= " + parsed.getError()); return null; } if (parsed.getOptions() == null || parsed.getOptions().size() == 0) { log.warn("No options returned from UPS"); return null; } String carrier = getShippingMethodDescription(locale); // cost is in CAD, need to do conversion /* * boolean requiresCurrencyConversion = false; String storeCurrency * = store.getCurrency(); * if(!storeCurrency.equals(Constants.CURRENCY_CODE_CAD)) { * requiresCurrencyConversion = true; } */ LabelUtil labelUtil = LabelUtil.getInstance(); Map serviceMap = com.salesmanager.core.util.ShippingUtil.buildServiceMap("upsxml", locale); /** Details on whit RT quote information to display **/ MerchantConfiguration rtdetails = config .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() + "]"); } } } /**/ Collection returnColl = null; List options = parsed.getOptions(); if (options != null) { Map selectedintlservices = (Map) config.getConfiguration("service-global-upsxml"); Iterator i = options.iterator(); while (i.hasNext()) { ShippingOption option = (ShippingOption) i.next(); // option.setCurrency(store.getCurrency()); StringBuffer description = new StringBuffer(); String code = option.getOptionCode(); option.setOptionCode(code); // get description String label = (String) serviceMap.get(code); if (label == null) { log.warn("UPSXML cannot find description for service code " + code); } option.setOptionName(label); description.append(option.getOptionName()); if (displayQuoteDeliveryTime == ShippingConstants.DISPLAY_RT_QUOTE_TIME) { if (!StringUtils.isBlank(option.getEstimatedNumberOfDays())) { description.append(" (").append(option.getEstimatedNumberOfDays()).append(" ") .append(labelUtil.getText(locale, "label.generic.days.lowercase")).append(")"); } } option.setDescription(description.toString()); // get currency if (!option.getCurrency().equals(store.getCurrency())) { option.setOptionPrice(CurrencyUtil.convertToCurrency(option.getOptionPrice(), option.getCurrency(), store.getCurrency())); } if (!selectedintlservices.containsKey(option.getOptionCode())) { if (returnColl == null) { returnColl = new ArrayList(); } returnColl.add(option); // options.remove(option); } } if (options.size() == 0) { LogMerchantUtil.log(store.getMerchantId(), " none of the service code returned by UPS [" + selectedintlservices.keySet().toArray(new String[selectedintlservices.size()]) + "] for this shipping is in your selection list"); } } return returnColl; } catch (Exception e1) { log.error(e1); return null; } finally { if (reader != null) { try { reader.close(); } catch (Exception ignore) { } } if (httppost != null) { httppost.releaseConnection(); } } }
From source file:op.care.prescription.PnlScheduleDose.java
private void initPanel() { tabWdh.setTitleAt(0, SYSTools.xx("misc.msg.daily")); tabWdh.setTitleAt(1, SYSTools.xx("misc.msg.weekly")); tabWdh.setTitleAt(2, SYSTools.xx("misc.msg.monthly")); lblLDate.setText(SYSTools.xx(internalClassID + ".lblLDate") + " "); lblOnThe.setText(SYSTools.xx(internalClassID + ".lblOnThe")); lblMonth.setText(SYSTools.xx("misc.msg.months")); lblEach.setText(SYSTools.xx("misc.msg.every")); lblEvery1.setText(SYSTools.xx("misc.msg.every")); lblEvery2.setText(SYSTools.xx("misc.msg.every")); lblWeeksAt.setText(SYSTools.xx("misc.msg.weeks") + " " + SYSTools.xx("misc.msg.atchrono")); lblDays.setText(SYSTools.xx("misc.msg.Days2")); ArrayList<Date> timelist = SYSCalendar.getTimeList(); cmbUhrzeit.setModel(new DefaultComboBoxModel(timelist.toArray())); cmbUhrzeit.setRenderer(SYSCalendar.getTimeRenderer()); String[] wdaymodel = new String[] { SYSTools.xx("misc.msg.dayOfMonth"), SYSTools.xx("misc.msg.monday"), SYSTools.xx("misc.msg.tuesday"), SYSTools.xx("misc.msg.wednesday"), SYSTools.xx("misc.msg.thursday"), SYSTools.xx("misc.msg.friday"), SYSTools.xx("misc.msg.saturday"), SYSTools.xx("misc.msg.sunday") }; cmbWDay.setModel(new DefaultComboBoxModel(wdaymodel)); lblMon.setText(SYSTools.xx("misc.msg.monday")); lblTue.setText(SYSTools.xx("misc.msg.tuesday")); lblWed.setText(SYSTools.xx("misc.msg.wednesday")); lblThu.setText(SYSTools.xx("misc.msg.thursday")); lblFri.setText(SYSTools.xx("misc.msg.friday")); lblSat.setText(SYSTools.xx("misc.msg.saturday")); lblSun.setText(SYSTools.xx("misc.msg.sunday")); lblVeryEarly.setText(SYSTools.xx("misc.msg.earlyinthemorning.long")); lblMorning.setText(SYSTools.xx("misc.msg.morning.long")); lblNoon.setText(SYSTools.xx("misc.msg.noon.long")); lblAfternoon.setText(SYSTools.xx("misc.msg.afternoon.long")); lblEvening.setText(SYSTools.xx("misc.msg.evening.long")); lblVeryLate.setText(SYSTools.xx("misc.msg.lateatnight.long")); txtEveryDay.setText("1"); txtEveryWeek.setText("1"); txtEveryMonth.setText("1"); txtEveryWDayOfMonth.setText("1"); // txtEveryDay.setText(schedule.getTaeglich().toString()); // txtEveryWeek.setText(schedule.getWoechentlich().toString()); // txtEveryMonth.setText(schedule.getMonatlich().toString()); // txtEveryWDayOfMonth.setText(schedule.getTagNum().toString()); tabWdh.setSelectedIndex(TAB_DAILY);//ww w . j a va 2s. com if (schedule.getWoechentlich() > 0) { cbMon.setSelected(schedule.getMon() > 0); cbTue.setSelected(schedule.getTue() > 0); cbWed.setSelected(schedule.getWed() > 0); cbThu.setSelected(schedule.getThu() > 0); cbFri.setSelected(schedule.getFri() > 0); cbSat.setSelected(schedule.getSat() > 0); cbSun.setSelected(schedule.getSun() > 0); tabWdh.setSelectedIndex(TAB_WEEKLY); } if (schedule.getMonatlich() > 0) { if (schedule.getTagNum() > 0) { txtEveryWDayOfMonth.setText(Short.toString(schedule.getTagNum())); cmbWDay.setSelectedIndex(0); } else { if (schedule.getMon() > 0) { cmbWDay.setSelectedIndex(1); txtEveryWDayOfMonth.setText(Short.toString(schedule.getMon())); } else if (schedule.getTue() > 0) { cmbWDay.setSelectedIndex(2); txtEveryWDayOfMonth.setText(Short.toString(schedule.getTue())); } else if (schedule.getWed() > 0) { cmbWDay.setSelectedIndex(3); txtEveryWDayOfMonth.setText(Short.toString(schedule.getWed())); } else if (schedule.getThu() > 0) { cmbWDay.setSelectedIndex(4); txtEveryWDayOfMonth.setText(Short.toString(schedule.getThu())); } else if (schedule.getFri() > 0) { cmbWDay.setSelectedIndex(5); txtEveryWDayOfMonth.setText(Short.toString(schedule.getFri())); } else if (schedule.getSat() > 0) { cmbWDay.setSelectedIndex(6); txtEveryWDayOfMonth.setText(Short.toString(schedule.getSat())); } else if (schedule.getSun() > 0) { cmbWDay.setSelectedIndex(7); txtEveryWDayOfMonth.setText(Short.toString(schedule.getSun())); } } tabWdh.setSelectedIndex(TAB_MONTHLY); } // jdcLDatum.setMinSelectableDate(new Date()); // jdcLDatum.setDate(new Date(Math.max(schedule.getLDatum().getTime(), SYSCalendar.startOfDay()))); DateMidnight scheduleLDate = new DateMidnight(schedule.getLDatum()); DateMidnight today = new DateMidnight(); DateMidnight ldate = new DateMidnight(Math.max(scheduleLDate.getMillis(), today.getMillis())); txtLDate.setText(DateFormat.getDateInstance().format(ldate.toDate())); txtVeryEarly.setText(schedule.getNachtMo().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); txtMorning.setText(schedule.getMorgens().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); txtNoon.setText(schedule.getMittags().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); txtAfternoon.setText(schedule.getNachmittags().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); txtEvening.setText(schedule.getAbends().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); txtVeryLate.setText(schedule.getNachtAb().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); txtTimeDose.setText(schedule.getUhrzeitDosis().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); txtMorning.setBackground(SYSConst.lightblue); txtNoon.setBackground(SYSConst.gold7); txtAfternoon.setBackground(SYSConst.melonrindgreen); txtEvening.setBackground(SYSConst.bermuda_sand); txtVeryLate.setBackground(SYSConst.bluegrey); Date now = null; if (schedule.getUhrzeitDosis().compareTo(BigDecimal.ZERO) > 0) { splitRegularPos = 0.0d; now = schedule.getUhrzeit(); } else { now = new Date(); splitRegularPos = 1.0d; } for (Date zeit : timelist) { if (SYSCalendar.compareTime(zeit, now) >= 0) { now = zeit; break; } } cmbUhrzeit.setSelectedItem(now); lblTimeDose.setText(SYSTools.xx(internalClassID + ".lblTimeDose") + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now) + " " + SYSTools.xx("misc.msg.Time.short")); panelMainComponentResized(null); }
From source file:churashima.action.manage.ExpensesAction.java
@Execute(validator = false) public String editExecute() { ExpensesDao expensesDao = SingletonS2Container.getComponent(ExpensesDao.class); Expenses expenses = expensesDao.selectById(Long.valueOf(expensesForm.expensesId)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); try {/*from www. java 2 s . c o m*/ expenses.date = sdf.parse(expensesForm.strDate); } catch (ParseException e) { e.printStackTrace(); } expenses.subjectId = expensesForm.subjectId; expenses.place = expensesForm.place; expenses.name = expensesForm.name; expenses.price = expensesForm.price; expenses.category = expensesForm.category; expenses.categoryDetail = expensesForm.detail; expenses.openFlg = expensesForm.openFlg; expenses.comment = expensesForm.comment; expenses.isExcludeTax = expensesForm.isExcludeTax; TaxDao taxDao = SingletonS2Container.getComponent(TaxDao.class); BigDecimal tax = taxDao.selectByDate(expenses.date); if (Const.TAX_EXCLUDE.equals(expensesForm.isExcludeTax)) { // ????? expenses.priceTax = expensesForm.price.multiply(tax); expenses.priceExcludeTax = expensesForm.price; expenses.price = expenses.priceExcludeTax.add(expenses.priceTax); } else { // ???? expenses.price = expensesForm.price; expenses.priceExcludeTax = expensesForm.price.divide(BigDecimal.valueOf(1).add(tax), 3, BigDecimal.ROUND_HALF_UP); // ? expenses.priceTax = expenses.price.subtract(expenses.priceExcludeTax); } expensesDao.update(expenses); if ("expensesList".equals(expensesForm.fromPageId)) { // ?????? return "search"; } else { // ?????? return "/manage/expenses"; } }
From source file:com.yucheng.cmis.pvp.app.component.PvpAuthorizeComponent.java
/** * ??/*from w w w. j a va 2s .com*/ * * * * *120= * @param rate * @return */ public static String getCoreTradeRate(Double rate) { BigDecimal reality = new BigDecimal(rate); reality = reality.multiply(new BigDecimal(120)); reality = reality.divide(new BigDecimal(1), 5, BigDecimal.ROUND_HALF_UP); return reality.toPlainString(); }