List of usage examples for java.math BigDecimal doubleValue
@Override public double doubleValue()
From source file:com.salesmanager.core.service.shipping.ShippingService.java
/** * Calculates shipping cost based on shipping modules configured Will return * ShippingOptions/*from www . j a v a2 s. c o m*/ */ @Transactional public ShippingInformation getShippingQuote(Collection<OrderProduct> orderProducts, Customer customer, int merchantId, Locale locale, String currency) throws Exception { LabelUtil label = LabelUtil.getInstance(); label.setLocale(locale); ShippingInformation shippingInfo = new ShippingInformation(); String shippingType = ShippingConstants.DOMESTIC_SHIPPING; Collection<ShippingMethod> shippingMethods = null; double shippingWeight = 0; int quoteMethodCount = 0; MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService); MerchantStore store = mservice.getMerchantStore(merchantId); Map allCountries = RefCache.getCountriesMap(); // origin country Country c = (Country) allCountries.get(store.getCountry()); if (c == null) { LogMerchantUtil.log(merchantId, "Cannot identify country id " + store.getCountry() + " please make sure it is configured in Store menu option."); log.error("Cannot identify origin countryId " + store.getCountry()); String message = label.getText(locale, "error.cart.origincountry"); shippingInfo.setMessage(message); return shippingInfo; } int customerCountryId = customer.getCustomerCountryId(); // destination Country customerCountry = (Country) allCountries.get(customerCountryId); if (customerCountry == null) { log.error("Cannot identify destination countryId " + customerCountryId); String message = label.getText(locale, "error.cart.destinationcountry"); shippingInfo.setMessage(message); return shippingInfo; } if (store.getCountry() != customer.getCustomerCountryId()) { shippingType = ShippingConstants.INTERNATIONAL_SHIPPING; } // get shipping informations ConfigurationRequest request = new ConfigurationRequest(merchantId, true, "SHP_"); ConfigurationResponse response = mservice.getConfiguration(request); // are there any module configured MerchantConfiguration rtconf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_RT_MODULE_INDIC_NAME); MerchantConfiguration custconf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_INDIC_COUNTRIES_COSTS); if ((rtconf == null && custconf == null) || (rtconf != null && !StringUtils.isBlank(rtconf.getConfigurationValue()) && rtconf.getConfigurationValue().equals("false")) && (custconf != null && !StringUtils.isBlank(custconf.getConfigurationValue()) && custconf != null && custconf.getConfigurationValue().equals("false"))) {// no module // configured LogMerchantUtil.log(merchantId, "No shipping module configured yet"); String message = label.getText(locale, "error.cart.noshippingconfigured"); shippingInfo.setMessage(message); return shippingInfo; } // get shipping type // national or international MerchantConfiguration shippingTypeConf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_ZONES_SHIPPING); if (shippingType != null && StringUtils.isBlank(shippingTypeConf.getConfigurationValue())) { String sType = shippingTypeConf.getConfigurationValue(); if (sType.equals(ShippingConstants.DOMESTIC_SHIPPING) && store.getCountry() != customer.getCustomerCountryId()) { // set shipping message String message = label.getText(locale, "error.cart.noshippinginternational"); shippingInfo.setMessage(message); return shippingInfo; } } // is the shipping country from the exclusion list MerchantConfiguration excluconf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_ZONES_SKIPPED); if (excluconf != null && !StringUtils.isBlank(excluconf.getConfigurationValue())) { Map excludeMap = StringUtil.parseTokenLine(excluconf.getConfigurationValue(), ";"); if (excludeMap.containsKey(customerCountry.getCountryIsoCode2())) { String message = label.getText(locale, "error.cart.noshippinginternational"); shippingInfo.setMessage(message); return shippingInfo; } } // Calculate orderTotal for items to be shipped BigDecimal orderTotal = new BigDecimal("0"); Iterator orderProductsIterator = orderProducts.iterator(); while (orderProductsIterator.hasNext()) { OrderProduct op = (OrderProduct) orderProductsIterator.next(); if (op.isShipping()) { BigDecimal finalPrice = op.getFinalPrice(); BigDecimal priceTax = op.getProductTax(); orderTotal = orderTotal.add(finalPrice).add(priceTax); } } // invoke packing module for getting details on the packages Collection<PackageDetail> packages = null; MerchantConfiguration conf = response.getMerchantConfiguration(ShippingConstants.PACKING_CONFIGURATION_KEY); if (conf != null) { String packingModule = conf.getConfigurationValue(); if (!StringUtils.isBlank(packingModule)) { CalculatePackingModule module = (CalculatePackingModule) SpringUtil.getBean(packingModule); try { packages = module.calculatePacking(orderProducts, conf, merchantId); } catch (Exception e) { // use standard packing if (!packingModule.equals(ShippingConstants.DEFAULT_PACKING_MODULE)) { module = (CalculatePackingModule) SpringUtil .getBean(ShippingConstants.DEFAULT_PACKING_MODULE); packages = module.calculatePacking(orderProducts, conf, merchantId); } } } } if (packages == null) {// calculate packages per item packages = new ArrayList(); orderProductsIterator = orderProducts.iterator(); while (orderProductsIterator.hasNext()) { OrderProduct op = (OrderProduct) orderProductsIterator.next(); if (!op.isShipping()) { continue; } BigDecimal weight = op.getProductWeight(); Set attributes = op.getOrderattributes(); if (attributes != null && attributes.size() > 0) { Iterator attributesIterator = attributes.iterator(); OrderProductAttribute opa = (OrderProductAttribute) attributesIterator.next(); weight = weight.add(opa.getProductAttributeWeight()); } if (op.getProductQuantity() == 1) { PackageDetail detail = new PackageDetail(); detail.setCurrency(currency); detail.setShippingHeight(op.getProductHeight().doubleValue()); detail.setShippingLength(op.getProductLength().doubleValue()); detail.setShippingWeight(weight.doubleValue()); detail.setShippingWidth(op.getProductWidth().doubleValue()); detail.setShippingQuantity(op.getProductQuantity()); detail.setProductName(op.getProductName()); packages.add(detail); } else if (op.getProductQuantity() > 1) { for (int i = 0; i < op.getProductQuantity(); i++) { PackageDetail inner = new PackageDetail(); inner.setCurrency(currency); inner.setShippingHeight(op.getProductHeight().doubleValue()); inner.setShippingLength(op.getProductLength().doubleValue()); inner.setShippingWeight(weight.doubleValue()); inner.setShippingWidth(op.getProductWidth().doubleValue()); inner.setShippingQuantity(op.getProductQuantity()); inner.setProductName(op.getProductName()); packages.add(inner); } } } } if (packages != null) { Iterator packIter = packages.iterator(); while (packIter.hasNext()) { PackageDetail detail = (PackageDetail) packIter.next(); detail.setProductName("N/A"); shippingWeight = shippingWeight + detail.getShippingWeight(); } } // tax MerchantConfiguration taxconf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_TAX_CLASS); if (taxconf != null && !StringUtils.isBlank(taxconf.getConfigurationValue())) { long taxClassId = Long.parseLong(taxconf.getConfigurationValue()); shippingInfo.setTaxClass(taxClassId); } // handling fee BigDecimal handling = new BigDecimal("0"); MerchantConfiguration handlingconf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_HANDLING_FEES); if (handlingconf != null && !StringUtils.isBlank(handlingconf.getConfigurationValue())) { String shandling = handlingconf.getConfigurationValue(); try { handling = new BigDecimal(shandling); if (handling.doubleValue() > 0) { shippingInfo.setHandlingCost(handling); shippingInfo.setHandlingCostText( CurrencyUtil.displayFormatedAmountWithCurrency(handling, currency)); } } catch (Exception e) { log.error("Cannot parse handling fee to BigDecimal " + shandling); } } // invoke configured modules List configList = response.getMerchantConfigurationList(); Iterator configListIterator = configList.iterator(); while (configListIterator.hasNext()) { MerchantConfiguration gatewayconf = (MerchantConfiguration) configListIterator.next(); if (gatewayconf.getConfigurationKey().equals(ShippingConstants.MODULE_SHIPPING_RT_MODULE_INDIC_NAME)) { if (gatewayconf != null && !StringUtils.isBlank(gatewayconf.getConfigurationValue()) && gatewayconf.getConfigurationValue().equals("true")) { String module = gatewayconf.getConfigurationValue1(); if (StringUtils.isBlank(module)) { log.warn( "RT Shipping module is not configured appropriatly, the column module should contain module name, see configuration id " + gatewayconf.getConfigurationId()); } else { ShippingQuotesModule shippingModule = (ShippingQuotesModule) SpringUtil.getBean(module); if (shippingModule == null) { log.error("Shipping module " + module + " is not defined in sm-modules.xml"); } else { // check if module can be applied to store CoreModuleService cms = getRealTimeQuoteShippingService( CountryUtil.getCountryIsoCodeById(store.getCountry()), module); if (cms != null) {// this shipping method cannot be // used Collection rtOptions = shippingModule.getShippingQuote(response, orderTotal, packages, customer, store, locale); if (rtOptions != null) { // check for quote comparaison MerchantConfiguration rtdetails = response.getMerchantConfiguration( ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES); int quoteDisplayType = ShippingConstants.ALL_QUOTES_DISPLAYED; if (rtdetails != null) { if (!StringUtils.isBlank(rtdetails.getConfigurationValue2())) {// display // or // not // quotes try { quoteDisplayType = Integer .parseInt(rtdetails.getConfigurationValue2()); } catch (Exception e) { log.error("Display quote types is not an integer value [" + rtdetails.getConfigurationValue2() + "]"); } } } if (quoteDisplayType == ShippingConstants.LESS_EXPENSIVE_QUOTE_DISPLAYED || quoteDisplayType == ShippingConstants.MAX_EXPENSIVE_QUOTE_DISPLAYED) { Iterator rtOptionsIterator = rtOptions.iterator(); ShippingOption currentOption = null; while (rtOptionsIterator.hasNext()) { ShippingOption option = (ShippingOption) rtOptionsIterator.next(); if (currentOption == null) { currentOption = option; } if (quoteDisplayType == ShippingConstants.LESS_EXPENSIVE_QUOTE_DISPLAYED) { if (option.getOptionPrice().longValue() < currentOption .getOptionPrice().longValue()) { currentOption = option; } } else if (quoteDisplayType == ShippingConstants.MAX_EXPENSIVE_QUOTE_DISPLAYED) { if (option.getOptionPrice().longValue() > currentOption .getOptionPrice().longValue()) { currentOption = option; } } } rtOptions = new ArrayList(); rtOptions.add(currentOption); } ShippingMethod method = new ShippingMethod(); method.setShippingModule(module); method.setShippingMethodName( shippingModule.getShippingMethodDescription(locale)); quoteMethodCount++; if (shippingMethods == null) { shippingMethods = new ArrayList(); } method.setOptions(rtOptions); method.setImage(cms.getCoreModuleServiceLogoPath()); method.setPriority(0); shippingMethods.add(method); } } } } } } } // invoke custom module MerchantConfiguration customconf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_INDIC_COUNTRIES_COSTS); if (customconf != null && !StringUtils.isBlank(customconf.getConfigurationValue()) && customconf.getConfigurationValue().equals("true")) { // parse first column Map cs = StringUtil.parseTokenLine(customconf.getConfigurationValue1(), "|"); Map countries = new HashMap(); if (cs != null && cs.size() > 0) { for (Object o : cs.keySet()) { String k = (String) o; if (!k.contains(";")) { countries.put(k, (Integer) cs.get(k)); continue; } StringTokenizer st = new StringTokenizer(k, ";"); while (st.hasMoreTokens()) { String t = st.nextToken(); countries.put(t, (Integer) cs.get(k)); } } } if (countries.containsKey(customerCountry.getCountryIsoCode2())) { // get estimate String shippingEstimateLine = null; String shippingCostLine = customconf.getConfigurationValue1(); MerchantConfiguration estimateCountryConf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_ESTIMATE_BYCOUNTRY); if (estimateCountryConf != null && !StringUtils.isBlank(estimateCountryConf.getConfigurationValue1())) { shippingEstimateLine = estimateCountryConf.getConfigurationValue1(); } // contains index - ShippingPriceRegion Map priceTimeMap = ShippingUtil.buildShippingPriceRegionMap("", shippingCostLine, shippingEstimateLine); // determine index int index = -1; if (!StringUtils.isBlank(shippingCostLine)) { StringTokenizer cvtk = new StringTokenizer(shippingCostLine, "|"); int count = 1; while (cvtk.hasMoreTokens()) { if (index != -1) { break; } String countryline = cvtk.nextToken();// maxpound:price,maxpound:price...| if (!countryline.equals("*")) { StringTokenizer countrystk = new StringTokenizer(countryline, ";"); String country = null; while (countrystk.hasMoreTokens()) { country = countrystk.nextToken(); if (customerCountry.getCountryIsoCode2() != null && country.equals(customerCountry.getCountryIsoCode2())) { index = count; break; } } } count++; } } int iposition = (Integer) countries.get(customerCountry.getCountryIsoCode2());// index // need to get the prices / pounds Map data = StringUtil.parseTokenLine(customconf.getConfigurationValue2(), "|"); Map swapedData = ((BidiMap) data).inverseBidiMap(); String countryData = (String) swapedData.get(iposition); // this line is in the form [MAX_POUND:PRICE;MAX_POUND2:PRICE] // get boundaries ShippingMethod method = new ShippingMethod(); method.setShippingModule("custom"); String description = label.getText(locale, "message.cart.sellershippingcost") + " " + customerCountry.getCountryName() + " " + customer.getCustomerPostalCode(); method.setPriority(1); if (shippingMethods == null || shippingMethods.size() == 0) { method.setPriority(0); } method.setShippingMethodName(description); StringTokenizer st = new StringTokenizer(countryData, ";"); int lowBoundary = 0; while (st.hasMoreTokens()) { String token = st.nextToken();// should have MAX_POUND:PRICE try { int position = token.indexOf(":"); if (position > -1) { String spound = token.substring(0, token.indexOf(":")); if (spound != null) { int highBoundary = Integer.parseInt(spound); if (lowBoundary <= shippingWeight && highBoundary >= shippingWeight) { String sprice = token.substring(position + 1, token.length()); ShippingOption option = new ShippingOption(); option.setCurrency(store.getCurrency()); option.setOptionCode("custom"); option.setOptionId("custom-" + lowBoundary); option.setOptionPrice(new BigDecimal(sprice)); option.setDescription(description); method.addOption(option); if (shippingMethods == null) { shippingMethods = new ArrayList(); } shippingMethods.add(method); // get the estimate if (priceTimeMap != null && priceTimeMap.size() > 0) { ShippingPriceRegion spr = (ShippingPriceRegion) priceTimeMap.get(index); if (spr != null && spr.getMinDays() != -1 && spr.getMaxDays() != -1) { String returnText = ""; if (locale == null) { locale = LocaleUtil.getDefaultLocale(); } try { if (spr.getMinDays() == spr.getMaxDays()) { List parameters = new ArrayList(); parameters.add(customerCountry.getCountryIsoCode2()); parameters.add(spr.getMaxDays()); returnText = label.getText(locale, "message.delivery.estimate.precise", parameters); } else { List parameters = new ArrayList(); parameters.add(customerCountry.getCountryIsoCode2()); parameters.add(spr.getMinDays()); parameters.add(spr.getMaxDays()); returnText = label.getText(locale, "message.delivery.estimate.range", parameters); } option.setEstimatedNumberOfDays(returnText); } catch (Exception e) { log.error("Error assigning parameters for shipping"); } } } quoteMethodCount++; break; } lowBoundary = highBoundary; } } } catch (Exception e) { log.error("Price Pound parsing error " + e); } } } } if (quoteMethodCount == 0) { String message = LabelUtil.getInstance().getText(locale, "error.cart.noshippingconfigured"); shippingInfo.setMessage(message); return shippingInfo; } if (quoteMethodCount > 0) { // is it free ? MerchantConfiguration freeconf = response .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_FREE_IND_DEST_AMNT); if (freeconf != null && !StringUtils.isBlank(freeconf.getConfigurationValue()) && freeconf.getConfigurationValue().equals("true")) { // get national or international String freeShippingType = freeconf.getConfigurationValue1(); if (!StringUtils.isBlank(freeShippingType)) { // if shipping is domestic and free ship is domestic, then // ok // if shipping is domestic and free ship is intl, then ok // if shipping is intl and free ship is intl, then ok if (shippingType.equals(ShippingConstants.DOMESTIC_SHIPPING) || freeShippingType.equals(shippingType)) { // get amount if (!StringUtils.isBlank(freeconf.getConfigurationValue2())) { BigDecimal freeAmount = new BigDecimal(freeconf.getConfigurationValue2()).setScale(2); if (orderTotal.floatValue() - freeAmount.floatValue() > 0) { // remove live quotes shippingInfo.setShippingMethods(null); String message = LabelUtil.getInstance().getText(locale, "message.cart.freeshipping") + " " + CurrencyUtil.displayFormatedAmountWithCurrency(freeAmount, currency); shippingInfo.setMessage(message); BigDecimal freeShippingCost = new BigDecimal("0"); List optList = new ArrayList(); ShippingMethod method = new ShippingMethod(); method.setShippingMethodName( LabelUtil.getInstance().getText(locale, "label.cart.freeshipping")); method.setShippingModule("free"); method.setPriority(0); ShippingOption option = new ShippingOption(); option.setOptionId("free"); option.setCurrency(currency); option.setOptionCode("free"); option.setModule("free"); option.setOptionPrice(new BigDecimal("0")); option.setDescription( LabelUtil.getInstance().getText(locale, "label.cart.freeshipping") + " " + customerCountry.getCountryName() + " " + customer.getCustomerPostalCode()); optList.add(option); method.setOptions(optList); shippingMethods = new ArrayList(); shippingMethods.add(method); shippingInfo.setShippingCost(freeShippingCost); shippingInfo.setShippingCostText( CurrencyUtil.displayFormatedAmountWithCurrency(freeShippingCost, currency)); shippingInfo.setFreeShipping(true); // no handling fee shippingInfo.setHandlingCost(new BigDecimal("0")); } } } } } } if (shippingMethods != null) { shippingInfo.setShippingMethods(shippingMethods); } return shippingInfo; }
From source file:managedBean.MbVNotas.java
private void perdidosxAsistencia(List<ClsNotas> lstTblNotases) throws Exception { DaoTAsistencias daoTasistencia = new DaoTAsistencias(); DaoTHorarioModulo daoHorario = new DaoTHorarioModulo(); List<Asistencia> lstAsist = null; List<HorarioModulo> lstHorario = null; Object[] obj = null;//w ww .j a va 2s . c o m Object objHorario = null; Double sumaAsistencia = null; Double sumaHorario = null; BigDecimal porcentaje = null; if (this.clsTblModulosReg != null) { lstAsist = daoTasistencia.getPerdidosxAsistencia(this.clsTblModulosReg.getIdModulo()); lstHorario = daoHorario.getTotalHorasHorario(this.clsTblModulosReg.getIdModulo()); } else { lstAsist = daoTasistencia.getPerdidosxAsistencia(0); lstHorario = daoHorario.getTotalHorasHorario(0); } if (lstHorario.size() > 0) { objHorario = (Object) lstHorario.get(0); sumaHorario = ((BigDecimal) objHorario).doubleValue(); } if (lstAsist.size() > 0) { for (int i = 0; i < lstTblNotases.size(); i++) { for (int j = 0; j < lstAsist.size(); j++) { obj = (Object[]) (Object) lstAsist.get(j); if (obj[0].equals(lstTblNotases.get(i).getIdMatricula())) { sumaAsistencia = ((BigDecimal) obj[1]).doubleValue(); porcentaje = new BigDecimal((sumaAsistencia / sumaHorario) * 100); lstTblNotases.get(i).setTotalAsistencia(porcentaje.doubleValue()); } } } } }
From source file:com.visionet.platform.cooperation.service.OrderService.java
/** * ??/*from w w w . j a v a 2s .co m*/ * * @param meta * @return * @author ? */ public BigDecimal printInvoiceApplication(String meta) { if (StringUtils.isEmpty(meta)) { throw new BizException("meta??"); } MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class); Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo()); if (result == null) { throw new BizException("??"); } // ???? if (result.getStatus() != 2) { throw new BizException("??,??"); } BigDecimal invoice = new BigDecimal(0); if ("apply_invoice".equals(metaDto.getStatus())) { Customer customer = customerMapper.selectOneByPhone(result.getCustomerPhone()); if (customer != null) { if (result.getTotalPrice() < customer.getInvoiceBalance()) { invoice = new BigDecimal(result.getTotalPrice()); Double balance = customer.getInvoiceBalance() - invoice.doubleValue(); customer.setInvoiceBalance(balance); } else { invoice = new BigDecimal(customer.getInvoiceBalance()); customer.setInvoiceBalance(0d); } // ? customerMapper.updateByPrimaryKeySelective(customer); // ???? Order order = new Order(); order.setOrderId(metaDto.getPartnerOrderNo()); order.setIsInvoice(1);// order.setOtherPrice2(invoice.floatValue()); orderMapper.updateByPrimaryKeySelective(order); } } return invoice; }
From source file:helma.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet.// ww w. j a va 2s . c o m */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(safe); for (int i = 0; i < columns.length; i++) { int columnNumber = i + 1 + offset; // set prototype? if (columns[i].isPrototypeField()) { String protoId = rs.getString(columnNumber); protoName = dbm.getPrototypeName(protoId); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError("No prototype defined for prototype mapping \"" + protoName + "\" - Using default prototype \"" + dbm.getTypeName() + "\"."); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(columnNumber); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(columnNumber); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: case Types.BOOLEAN: newprop.setBooleanValue(rs.getBoolean(columnNumber)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(columnNumber)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(columnNumber)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(columnNumber); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: newprop.setJavaObjectValue(rs.getBytes(columnNumber)); break; case Types.BLOB: case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(columnNumber); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(columnNumber)); } catch (SQLException x) { Reader in = rs.getCharacterStream(columnNumber); if (in == null) { newprop.setStringValue(null); break; } StringBuffer out = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = in.read(buffer)) > -1) { out.append(buffer, 0, read); } newprop.setStringValue(out.toString()); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(columnNumber)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(columnNumber)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(columnNumber); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(columnNumber)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } else { Transactor tx = Transactor.getInstance(); if (tx != null) { // Check if the node is already registered with the transactor - // it may be in the process of being DELETED, but do return the // new node if the old one has been marked as INVALID. DbKey key = new DbKey(dbmap, id); Node dirtyNode = tx.getDirtyNode(key); if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) { return dirtyNode; } } } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && rel.isPrimitiveOrReference()) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if (rel.isReference() && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel); } propMap.put(rel.propName, prop); } } node.init(dbmap, id, name, protoName, propMap); return node; }
From source file:it.govpay.web.rs.dars.monitoraggio.versamenti.VersamentiHandler.java
@Override public Dettaglio getDettaglio(long id, UriInfo uriInfo, BasicBD bd) throws WebApplicationException, ConsoleException { String methodName = "dettaglio " + this.titoloServizio + "." + id; try {/*from w w w . j a v a2 s . c om*/ this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita); boolean eseguiRicerca = !setDomini.isEmpty(); List<Long> idDomini = new ArrayList<Long>(); VersamentiBD versamentiBD = new VersamentiBD(bd); if (eseguiRicerca && !setDomini.contains(-1L)) { VersamentoFilter filter = versamentiBD.newFilter(); List<Long> lstCodDomini = new ArrayList<Long>(); lstCodDomini.addAll(setDomini); idDomini.addAll(setDomini); filter.setIdDomini(idDomini); List<Long> idVersamentoL = new ArrayList<Long>(); idVersamentoL.add(id); filter.setIdVersamento(idVersamentoL); long count = eseguiRicerca ? versamentiBD.count(filter) : 0; eseguiRicerca = eseguiRicerca && count > 0; } // recupero oggetto Versamento versamento = eseguiRicerca ? versamentiBD.getVersamento(id) : null; InfoForm infoModifica = null; InfoForm infoCancellazione = versamento != null ? this.getInfoCancellazioneDettaglio(uriInfo, bd, versamento) : null; InfoForm infoEsportazione = versamento != null ? this.getInfoEsportazioneDettaglio(uriInfo, bd, versamento) : null; String titolo = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".dettaglioVersamento"); Dettaglio dettaglio = new Dettaglio(titolo, infoEsportazione, infoCancellazione, infoModifica); it.govpay.web.rs.dars.model.Sezione root = dettaglio.getSezioneRoot(); if (versamento != null) { // Applicazione Applicazione applicazione = versamento.getApplicazione(bd); if (applicazione != null) { root.addVoce(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".applicazione.label"), applicazione.getCodApplicazione()); } if (StringUtils.isNotEmpty(versamento.getCodVersamentoEnte())) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".codVersamentoEnte.label"), versamento.getCodVersamentoEnte()); } // Uo UnitaOperativa uo = versamento.getUo(bd); if (uo != null) { Dominio dominio = uo.getDominio(bd); Domini dominiDars = new Domini(); Elemento elemento = ((DominiHandler) dominiDars.getDarsHandler()).getElemento(dominio, dominio.getId(), dominiDars.getPathServizio(), bd); root.addVoce(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".idDominio.label"), elemento.getTitolo()); } // iuv Iuv iuv = versamento.getIuv(bd); if (iuv != null) { root.addVoce(Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".iuv.label"), iuv.getIuv()); } if (versamento.getCausaleVersamento() != null) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".causaleVersamento.label"), versamento.getCausaleVersamento().toString()); } if (versamento.getImportoTotale() != null) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".importoTotale.label"), versamento.getImportoTotale().toString() + ""); } if (versamento.getStatoVersamento() != null) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".statoVersamento.label"), Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".statoVersamento." + versamento.getStatoVersamento())); } if (StringUtils.isNotEmpty(versamento.getDescrizioneStato())) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".descrizioneStato.label"), versamento.getDescrizioneStato()); } if (versamento.getDataCreazione() != null) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".dataCreazione.label"), this.sdf.format(versamento.getDataCreazione())); } if (versamento.getDataScadenza() != null) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".dataScadenza.label"), this.sdf.format(versamento.getDataScadenza())); } if (versamento.getDataUltimoAggiornamento() != null) { root.addVoce( Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".dataUltimoAggiornamento.label"), this.sdf.format(versamento.getDataUltimoAggiornamento())); } root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".aggiornabile.label"), Utils.getSiNoAsLabel(versamento.isAggiornabile())); // Sezione Anagrafica Debitore Anagrafica anagrafica = versamento.getAnagraficaDebitore(); it.govpay.web.rs.dars.model.Sezione sezioneAnagrafica = dettaglio .addSezione(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + "." + ANAGRAFICA_DEBITORE + ".titolo")); AnagraficaHandler anagraficaHandler = new AnagraficaHandler(ANAGRAFICA_DEBITORE, this.nomeServizio, this.pathServizio, this.getLanguage()); anagraficaHandler.fillSezioneAnagraficaUO(sezioneAnagrafica, anagrafica); // Singoli Versamenti List<SingoloVersamento> singoliVersamenti = versamento.getSingoliVersamenti(bd); if (!Utils.isEmpty(singoliVersamenti)) { SingoliVersamenti svDars = new SingoliVersamenti(); Tributi trDars = new Tributi(); if (singoliVersamenti != null && singoliVersamenti.size() > 0) { for (SingoloVersamento entry : singoliVersamenti) { String etichettaSingoliVersamenti = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle( this.nomeServizio + ".elementoCorrelato.singoloVersamento.titolo"); it.govpay.web.rs.dars.model.Sezione sezioneSingoloVersamento = dettaglio .addSezione(etichettaSingoliVersamenti); sezioneSingoloVersamento.addVoce( Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( svDars.getNomeServizio() + ".codSingoloVersamentoEnte.label"), entry.getCodSingoloVersamentoEnte()); BigDecimal importoSingoloVersamento = entry.getImportoSingoloVersamento() != null ? entry.getImportoSingoloVersamento() : BigDecimal.ZERO; sezioneSingoloVersamento.addVoce( Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( svDars.getNomeServizio() + ".importoSingoloVersamento.label"), importoSingoloVersamento.doubleValue() + ""); Tributo tributo = entry.getTributo(bd); if (tributo != null) { sezioneSingoloVersamento.addVoce( Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( svDars.getNomeServizio() + ".tributo.label"), tributo.getDescrizione()); IbanAccredito ibanAccredito = tributo.getIbanAccredito(bd); if (ibanAccredito != null) sezioneSingoloVersamento .addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(svDars.getNomeServizio() + ".ibanAccredito.label"), ibanAccredito.getCodIban()); StringBuilder sb = new StringBuilder(); TipoContabilta tipoContabilita = entry.getTipoContabilita(bd) != null ? entry.getTipoContabilita(bd) : TipoContabilta.CAPITOLO; String tipoContabilitaValue = null; switch (tipoContabilita) { case ALTRO: tipoContabilitaValue = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle( trDars.getNomeServizio() + ".tipoContabilita.altro"); break; case SPECIALE: tipoContabilitaValue = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle( trDars.getNomeServizio() + ".tipoContabilita.speciale"); break; case SIOPE: tipoContabilitaValue = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle( trDars.getNomeServizio() + ".tipoContabilita.siope"); break; case CAPITOLO: default: tipoContabilitaValue = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle( trDars.getNomeServizio() + ".tipoContabilita.capitolo"); break; } String codContabilitaValue = StringUtils.isNotEmpty(entry.getCodContabilita(bd)) ? entry.getCodContabilita(bd) : "--"; sb.append(tipoContabilitaValue).append("/").append(codContabilitaValue); sezioneSingoloVersamento .addVoce( Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( svDars.getNomeServizio() + ".contabilita.label"), sb.toString()); } } } } Transazioni transazioniDars = new Transazioni(); String etichettaTransazioni = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".elementoCorrelato.transazioni.titolo"); String versamentoId = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(transazioniDars.getNomeServizio() + ".idVersamento.id"); Map<String, String> params = new HashMap<String, String>(); params = new HashMap<String, String>(); params.put(versamentoId, versamento.getId() + ""); URI transazioneDettaglio = Utils.creaUriConParametri(transazioniDars.getPathServizio(), params); dettaglio.addElementoCorrelato(etichettaTransazioni, transazioneDettaglio); } this.log.info("Esecuzione " + methodName + " completata."); return dettaglio; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }
From source file:it.greenvulcano.gvesb.datahandling.dbo.DBOCallSP.java
/** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, * java.lang.String, java.lang.String) */// ww w . j ava 2 s.co m @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (ROW_NAME.equals(localName)) { if (!currCriticalError) { executeStatement(); } else { rowDisc++; // aggiunta DiscardCause al dhr... String msg = currentXSLMessage; dhr.addDiscardCause(new DiscardCause(rowCounter, msg)); resultMessage.append("Data error on row ").append(rowCounter).append(": ").append(msg); resultMessage.append("SQL Statement Informations:\n").append(sqlStatementInfo); resultMessage.append("Record parameters:\n").append(dumpCurrentRowFields()); resultStatus = STATUS_PARTIAL; } } else if (COL_NAME.equals(localName)) { CallableStatement cs = (CallableStatement) sqlStatementInfo.getStatement(); try { if (!outOnly) { colDataExpecting = false; String text = textBuffer.toString(); if ((currentUUID != null) && (currentUUID.trim().length() > 0) && (text.length() == 0)) { text = uuids.get(currentUUID); if (text == null) { text = currentUUID; } } if (TIMESTAMP_TYPE.equals(currType) || DATE_TYPE.equals(currType) || TIME_TYPE.equals(currType)) { if (text.equals("")) { if (TIMESTAMP_TYPE.equals(currType)) setNull(cs, Types.TIMESTAMP); else if (DATE_TYPE.equals(currType)) setNull(cs, Types.DATE); else setNull(cs, Types.TIME); currentRowFields.add(null); } else { dateFormatter.applyPattern(currDateFormat); Date formattedDate = dateFormatter.parse(text); if (TIMESTAMP_TYPE.equals(currType)) { Timestamp ts = new Timestamp(formattedDate.getTime()); setTimestamp(cs, ts); currentRowFields.add(ts); } else if (DATE_TYPE.equals(currType)) { java.sql.Date d = new java.sql.Date(formattedDate.getTime()); setDate(cs, d); currentRowFields.add(d); } else { java.sql.Time t = new java.sql.Time(formattedDate.getTime()); setTime(cs, t); currentRowFields.add(t); } } } else if (INTEGER_TYPE.equals(currType) || SMALLINT_TYPE.equals(currType) || BIGINT_TYPE.equals(currType)) { if (text.equals("")) { if (INTEGER_TYPE.equals(currType)) setNull(cs, Types.INTEGER); else if (SMALLINT_TYPE.equals(currType)) setNull(cs, Types.SMALLINT); else setNull(cs, Types.BIGINT); currentRowFields.add(null); } else { if (INTEGER_TYPE.equals(currType)) setInt(cs, Integer.parseInt(text, 10)); else if (SMALLINT_TYPE.equals(currType)) setShort(cs, Short.parseShort(text, 10)); else setLong(cs, Long.parseLong(text, 10)); currentRowFields.add(text); } } else if (FLOAT_TYPE.equals(currType) || DOUBLE_TYPE.equals(currType) || DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { if (text.equals("")) { if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) setNull(cs, Types.NUMERIC); else if (FLOAT_TYPE.equals(currType)) setNull(cs, Types.FLOAT); else setNull(cs, Types.DOUBLE); currentRowFields.add(null); } else { DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols(); dfs.setDecimalSeparator(currDecSeparator.charAt(0)); dfs.setGroupingSeparator(currGroupSeparator.charAt(0)); numberFormatter.setDecimalFormatSymbols(dfs); numberFormatter.applyPattern(currNumberFormat); boolean isBigDecimal = numberFormatter.isParseBigDecimal(); try { numberFormatter.setParseBigDecimal(true); BigDecimal formattedNumber = (BigDecimal) numberFormatter.parse(text); if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { setBigDecimal(cs, formattedNumber); currentRowFields.add(formattedNumber); } else if (FLOAT_TYPE.equals(currType)) { setFloat(cs, formattedNumber.floatValue()); currentRowFields.add(formattedNumber.floatValue()); } else { setDouble(cs, formattedNumber.doubleValue()); currentRowFields.add(formattedNumber.doubleValue()); } } finally { numberFormatter.setParseBigDecimal(isBigDecimal); } } } else if (LONG_STRING_TYPE.equals(currType) || LONG_NSTRING_TYPE.equals(currType)) { if (text.equals("")) { if (LONG_STRING_TYPE.equals(currType)) setNull(cs, Types.CLOB); else setNull(cs, Types.NCLOB); currentRowFields.add(null); } else { if (LONG_STRING_TYPE.equals(currType)) { setCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } else { setNCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } } } else if (BASE64_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); data = Base64.getDecoder().decode(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BINARY_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BOOLEAN_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BOOLEAN); currentRowFields.add(null); } else { setBoolean(cs, TextUtils.parseBoolean(text)); currentRowFields.add(text); } } else if (XML_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.SQLXML); currentRowFields.add(null); } else { SQLXML xml = cs.getConnection().createSQLXML(); xml.setString(text); setSQLXML(cs, xml); currentRowFields.add(text); } } else if (NSTRING_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.NVARCHAR); currentRowFields.add(null); } else { setNString(cs, text); currentRowFields.add(text); } } else { if (text.equals("")) { setNull(cs, Types.VARCHAR); currentRowFields.add(null); } else { setString(cs, text); currentRowFields.add(text); } } } else { currentRowFields.add(currentUUID); } } catch (ParseException exc) { throw new SAXException(exc); } catch (SQLException exc) { OracleExceptionHandler.handleSQLException(exc); throw new SAXException(exc); } } }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
private Set<Long> addPredicateNumber(String theParamName, Set<Long> thePids, List<? extends IQueryParameterType> theList) { if (theList == null || theList.isEmpty()) { return thePids; }//from www . j a v a 2 s . c om CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceIndexedSearchParamNumber> from = cq.from(ResourceIndexedSearchParamNumber.class); cq.select(from.get("myResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; if (params instanceof NumberParam) { NumberParam param = (NumberParam) params; BigDecimal value = param.getValue(); if (value == null) { return thePids; } Path<Object> fromObj = from.get("myValue"); if (param.getComparator() == null) { double mul = value.doubleValue() * 1.01; double low = value.doubleValue() - mul; double high = value.doubleValue() + mul; Predicate lowPred = builder.ge(fromObj.as(Long.class), low); Predicate highPred = builder.le(fromObj.as(Long.class), high); codePredicates.add(builder.and(lowPred, highPred)); } else { switch (param.getComparator()) { case GREATERTHAN: codePredicates.add(builder.greaterThan(fromObj.as(BigDecimal.class), value)); break; case GREATERTHAN_OR_EQUALS: codePredicates.add(builder.ge(fromObj.as(BigDecimal.class), value)); break; case LESSTHAN: codePredicates.add(builder.lessThan(fromObj.as(BigDecimal.class), value)); break; case LESSTHAN_OR_EQUALS: codePredicates.add(builder.le(fromObj.as(BigDecimal.class), value)); break; } } } else { throw new IllegalArgumentException("Invalid token type: " + params.getClass()); } } Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0])); Predicate type = builder.equal(from.get("myResourceType"), myResourceName); Predicate name = builder.equal(from.get("myParamName"), theParamName); if (thePids.size() > 0) { Predicate inPids = (from.get("myResourcePid").in(thePids)); cq.where(builder.and(type, name, masterCodePredicate, inPids)); } else { cq.where(builder.and(type, name, masterCodePredicate)); } TypedQuery<Long> q = myEntityManager.createQuery(cq); return new HashSet<Long>(q.getResultList()); }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java
private double base30Tobase10Conversion(String base30String) { // new base(radix) number int oldBase = 30; //dbgLog.fine("base30String="+base30String); // trim white-spaces from the both ends String base30StringClean = StringUtils.trim(base30String); //dbgLog.fine("base30StringClean="+base30StringClean); // check the negative/positive sign boolean isNegativeNumber = false; boolean hasPositiveSign = false; if (base30StringClean.startsWith("-")) { isNegativeNumber = true;/* w ww .ja v a 2 s . c o m*/ } if (base30StringClean.startsWith("+")) { hasPositiveSign = true; } // remove the sign if exits String base30StringNoSign = null; if ((isNegativeNumber) || (hasPositiveSign)) { base30StringNoSign = base30StringClean.substring(1); } else { base30StringNoSign = new String(base30StringClean); } // check the scientific notation // if so, divide it into the significand and exponent String significand = null; long exponent = 0; int plusIndex = base30StringNoSign.indexOf("+"); int minusIndex = base30StringNoSign.indexOf("-"); if (plusIndex > 0) { significand = base30StringNoSign.substring(0, plusIndex); exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase); } else if (minusIndex > 0) { significand = base30StringNoSign.substring(0, minusIndex); exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase); } else { significand = new String(base30StringNoSign); } // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal int decimalIndex = significand.indexOf("."); if (decimalIndex != -1) { exponent -= (significand.length() - (decimalIndex + 1)); significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1); } MathContext mc = new MathContext(15, RoundingMode.HALF_UP); long base10Significand = Long.parseLong(significand, oldBase); BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc); BigDecimal exponentialComponent = new BigDecimal("1", mc); for (int g = 0; g < Math.abs(exponent); g++) { exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc)); } if (exponent >= 0) { base10value = base10value.multiply(exponentialComponent, mc); } else { base10value = base10value.divide(exponentialComponent, mc); } // negative sign if applicable if (isNegativeNumber) { base10value = base10value.multiply(new BigDecimal("-1", mc)); } return base10value.doubleValue(); }
From source file:com.viettel.logistic.wms.dao.StockGoodsSerialDAO.java
public Double getAmountInStockGoodsTotal(ChangePositionDTO changePositionDTO) { StringBuilder sql = new StringBuilder(); sql.append(" SELECT count(*) "); sql.append(" FROM wms_owner.stock_goods_serial a"); sql.append(" WHERE a.goods_id = ? "); sql.append(" AND a.owner_type = ? "); sql.append(" AND a.owner_id = ? "); sql.append(" AND a.cust_id = ? "); sql.append(" AND a.cell_code = ? "); sql.append(" AND a.status = ? "); List lstParams = new ArrayList<>(); lstParams.add(changePositionDTO.getGoodsId()); lstParams.add(changePositionDTO.getOwnerType()); lstParams.add(changePositionDTO.getStockId()); lstParams.add(changePositionDTO.getCustomerId()); lstParams.add(changePositionDTO.getCellCodeOld()); lstParams.add("1"); if (!DataUtil.isStringNullOrEmpty(changePositionDTO.getBarcode())) { sql.append(" AND a.barcode = ? "); lstParams.add(changePositionDTO.getBarcode()); }/*from www .ja v a2s .c om*/ SQLQuery query = getSession().createSQLQuery(sql.toString()); for (int idx = 0; idx < lstParams.size(); idx++) { query.setParameter(idx, lstParams.get(idx)); } List listResult = query.list(); BigDecimal result; if (listResult != null && listResult.size() > 0) { result = (BigDecimal) listResult.get(0); return result.doubleValue(); } return 0D; }
From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java
private double base30Tobase10Conversion(String base30String) { // new base(radix) number int oldBase = 30; //dbgLog.fine("base30String="+base30String); // trim white-spaces from the both ends String base30StringClean = StringUtils.trim(base30String); //dbgLog.fine("base30StringClean="+base30StringClean); // check the negative/positive sign boolean isNegativeNumber = false; boolean hasPositiveSign = false; if (base30StringClean.startsWith("-")) { isNegativeNumber = true;// www .ja va 2 s.c o m } if (base30StringClean.startsWith("+")) { hasPositiveSign = true; } // remove the sign if exits String base30StringNoSign = null; if ((isNegativeNumber) || (hasPositiveSign)) { base30StringNoSign = base30StringClean.substring(1); } else { base30StringNoSign = base30StringClean; } // check the scientific notation // if so, divide it into the significand and exponent String significand = null; long exponent = 0; int plusIndex = base30StringNoSign.indexOf("+"); int minusIndex = base30StringNoSign.indexOf("-"); if (plusIndex > 0) { significand = base30StringNoSign.substring(0, plusIndex); exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase); } else if (minusIndex > 0) { significand = base30StringNoSign.substring(0, minusIndex); exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase); } else { significand = base30StringNoSign; } // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal int decimalIndex = significand.indexOf("."); if (decimalIndex != -1) { exponent -= (significand.length() - (decimalIndex + 1)); significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1); } // TODO: Verify that the MathContext/Rounding methods are OK: // -- L.A. 4.0 beta MathContext mc = new MathContext(15, RoundingMode.HALF_UP); long base10Significand = Long.parseLong(significand, oldBase); BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc); BigDecimal exponentialComponent = new BigDecimal("1", mc); for (int g = 0; g < Math.abs(exponent); g++) { exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc)); } if (exponent >= 0) { base10value = base10value.multiply(exponentialComponent, mc); } else { base10value = base10value.divide(exponentialComponent, mc); } // negative sign if applicable if (isNegativeNumber) { base10value = base10value.multiply(new BigDecimal("-1", mc)); } return base10value.doubleValue(); }