List of usage examples for java.math BigDecimal doubleValue
@Override public double doubleValue()
From source file:com.willwinder.universalgcodesender.MainWindow.java
private void setStepSize(double val) { BigDecimal bd = new BigDecimal(val).setScale(3, RoundingMode.HALF_EVEN); val = bd.doubleValue(); this.stepSizeSpinner.setValue(val); }
From source file:com.hyeb.service.SearchServiceImpl.java
@SuppressWarnings("unchecked") @Transactional(readOnly = true)/* w ww . j a v a 2 s . com*/ public Page<Product> search(String keyword, BigDecimal startPrice, BigDecimal endPrice, OrderType orderType, Pageable pageable) { if (StringUtils.isEmpty(keyword)) { return new Page<Product>(); } if (pageable == null) { pageable = new Pageable(); } try { String text = QueryParser.escape(keyword); TermQuery snQuery = new TermQuery(new Term("sn", text)); Query keywordQuery = new QueryParser("keyword", new IKAnalyzer()).parse(text); QueryParser nameParser = new QueryParser("name", new IKAnalyzer()); nameParser.setDefaultOperator(QueryParser.AND_OPERATOR); Query nameQuery = nameParser.parse(text); FuzzyQuery nameFuzzyQuery = new FuzzyQuery(new Term("name", text), FUZZY_QUERY_MINIMUM_SIMILARITY); TermQuery introductionQuery = new TermQuery(new Term("introduction", text)); TermQuery isMarketableQuery = new TermQuery(new Term("isMarketable", "true")); TermQuery isListQuery = new TermQuery(new Term("isList", "true")); TermQuery isGiftQuery = new TermQuery(new Term("isGift", "false")); BooleanQuery textQuery = new BooleanQuery(); BooleanQuery query = new BooleanQuery(); textQuery.add(snQuery, Occur.SHOULD); textQuery.add(keywordQuery, Occur.SHOULD); textQuery.add(nameQuery, Occur.SHOULD); textQuery.add(nameFuzzyQuery, Occur.SHOULD); textQuery.add(introductionQuery, Occur.SHOULD); query.add(isMarketableQuery, Occur.MUST); query.add(isListQuery, Occur.MUST); query.add(isGiftQuery, Occur.MUST); query.add(textQuery, Occur.MUST); if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) { BigDecimal temp = startPrice; startPrice = endPrice; endPrice = temp; } if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0 && endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", startPrice.doubleValue(), endPrice.doubleValue(), true, true); query.add(numericRangeQuery, Occur.MUST); } else if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", startPrice.doubleValue(), null, true, false); query.add(numericRangeQuery, Occur.MUST); } else if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", null, endPrice.doubleValue(), false, true); query.add(numericRangeQuery, Occur.MUST); } FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Product.class); SortField[] sortFields = null; if (orderType == OrderType.priceAsc) { sortFields = new SortField[] { new SortField("price", SortField.Type.DOUBLE, false), new SortField("createDate", SortField.Type.LONG, true) }; } else if (orderType == OrderType.priceDesc) { sortFields = new SortField[] { new SortField("price", SortField.Type.DOUBLE, true), new SortField("createDate", SortField.Type.LONG, true) }; } else if (orderType == OrderType.salesDesc) { sortFields = new SortField[] { new SortField("sales", SortField.Type.INT, true), new SortField("createDate", SortField.Type.LONG, true) }; } else if (orderType == OrderType.scoreDesc) { sortFields = new SortField[] { new SortField("score", SortField.Type.INT, true), new SortField("createDate", SortField.Type.LONG, true) }; } else if (orderType == OrderType.dateDesc) { sortFields = new SortField[] { new SortField("createDate", SortField.Type.LONG, true) }; } else { sortFields = new SortField[] { new SortField("isTop", SortField.Type.STRING, true), new SortField(null, SortField.Type.SCORE), new SortField("modifyDate", SortField.Type.LONG, true) }; } fullTextQuery.setSort(new Sort(sortFields)); fullTextQuery.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize()); fullTextQuery.setMaxResults(pageable.getPageSize()); return new Page<Product>(fullTextQuery.getResultList(), fullTextQuery.getResultSize(), pageable); } catch (Exception e) { e.printStackTrace(); } return new Page<Product>(); }
From source file:org.esupportail.papercut.webportlet.EsupPapercutPortletController.java
@RequestMapping public ModelAndView renderView(RenderRequest request, RenderResponse response) { ModelMap model = new ModelMap(); model.put("htmlHeader", request.getPreferences().getValue("htmlHeader", "")); model.put("htmlFooter", request.getPreferences().getValue("htmlFooter", "")); model.put("payboxMontantMin", request.getPreferences().getValue("payboxMontantMin", "0.5")); model.put("payboxMontantMax", request.getPreferences().getValue("payboxMontantMax", "5.0")); model.put("payboxMontantStep", request.getPreferences().getValue("payboxMontantStep", "0.5")); model.put("payboxMontantDefaut", request.getPreferences().getValue("payboxMontantDefaut", "2.0")); double papercutSheetCost = Double.parseDouble(request.getPreferences().getValue("papercutSheetCost", "-1")); double papercutColorSheetCost = Double .parseDouble(request.getPreferences().getValue("papercutColorSheetCost", "-1")); String paperCutContext = request.getPreferences().getValue(PREF_PAPERCUT_CONTEXT, null); EsupPaperCutService esupPaperCutService = esupPaperCutServices.get(paperCutContext); String uid = getUid(request); String userMail = getUserMail(request); // check if the user can make a transaction int transactionNbMax = Integer.parseInt(request.getPreferences().getValue("transactionNbMax", "-1")); BigDecimal transactionMontantMax = new BigDecimal( request.getPreferences().getValue("transactionMontantMax", "-1")); boolean canMakeTransaction = true; // constraints via transactionNbMax if (transactionNbMax > -1) { long nbTransactionsNotArchived = PayboxPapercutTransactionLog .countFindPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid, paperCutContext, false); if (transactionNbMax <= nbTransactionsNotArchived) { canMakeTransaction = false;/*w w w. j a v a 2 s. com*/ } } BigDecimal payboxMontantMin = new BigDecimal(request.getPreferences().getValue("payboxMontantMin", "0.5")); BigDecimal payboxMontantMax = new BigDecimal(request.getPreferences().getValue("payboxMontantMax", "5.0")); BigDecimal payboxMontantStep = new BigDecimal( request.getPreferences().getValue("payboxMontantStep", "0.5")); BigDecimal payboxMontantDefaut = new BigDecimal( request.getPreferences().getValue("payboxMontantDefaut", "2.0")); // constraints on the slider via transactionMontantMax if (canMakeTransaction && transactionMontantMax.intValue() > -1) { List<PayboxPapercutTransactionLog> transactionsNotArchived = PayboxPapercutTransactionLog .findPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid, paperCutContext, false) .getResultList(); BigDecimal montantTotalTransactionsNotArchived = new BigDecimal("0"); for (PayboxPapercutTransactionLog txLog : transactionsNotArchived) { montantTotalTransactionsNotArchived = montantTotalTransactionsNotArchived .add(new BigDecimal(txLog.getMontant())); } transactionMontantMax = transactionMontantMax.multiply(new BigDecimal("100")) .subtract(montantTotalTransactionsNotArchived); if (transactionMontantMax.doubleValue() < payboxMontantMax.doubleValue() * 100) { payboxMontantMax = transactionMontantMax.divide(payboxMontantStep).multiply(payboxMontantStep); payboxMontantMax = payboxMontantMax.divide(new BigDecimal("100")); if (payboxMontantDefaut.compareTo(payboxMontantMax) == 1) { payboxMontantDefaut = payboxMontantMax; } if (payboxMontantMax.compareTo(payboxMontantMin) == -1) { canMakeTransaction = false; } model.put("payboxMontantMax", payboxMontantMax.doubleValue()); model.put("payboxMontantDefaut", payboxMontantDefaut.doubleValue()); } } // generation de l'ensemble des payboxForm : payboxMontantMin -> payboxMontantMax par pas de payboxMontantStep String portletContextPath = ((RenderResponse) response).createRenderURL().toString(); Map<Integer, PayBoxForm> payboxForms = new HashMap<Integer, PayBoxForm>(); for (BigDecimal montant = payboxMontantMin; montant.compareTo(payboxMontantMax) <= 0; montant = montant .add(payboxMontantStep)) { PayBoxForm payBoxForm = esupPaperCutService.getPayBoxForm(uid, userMail, montant.doubleValue(), paperCutContext, portletContextPath); if (papercutSheetCost > 0) { int nbSheets = (int) (montant.doubleValue() / papercutSheetCost); payBoxForm.setNbSheets(nbSheets); } if (papercutColorSheetCost > 0) { int nbColorSheets = (int) (montant.doubleValue() / papercutColorSheetCost); payBoxForm.setNbColorSheets(nbColorSheets); } payboxForms.put(montant.multiply(new BigDecimal(100)).intValue(), payBoxForm); } Map<Integer, PayBoxForm> sortedMap = new TreeMap<Integer, PayBoxForm>(payboxForms); model.put("payboxForms", sortedMap); model.put("payboxMontantDefautCents", payboxMontantDefaut.multiply(new BigDecimal(100)).intValue()); model.put("canMakeTransaction", canMakeTransaction); UserPapercutInfos userPapercutInfos = esupPaperCutService.getUserPapercutInfos(uid); model.put("userPapercutInfos", userPapercutInfos); boolean isAdmin = isAdmin(request); boolean isManager = isManager(request); model.put("isAdmin", isAdmin); model.put("isManager", isManager); model.put("active", "home"); return new ModelAndView(getViewName(request, "index"), model); }
From source file:net.groupbuy.service.impl.SearchServiceImpl.java
@SuppressWarnings("unchecked") @Transactional(readOnly = true)// ww w.j av a2 s. c o m public Page<Product> search(String keyword, BigDecimal startPrice, BigDecimal endPrice, OrderType orderType, Pageable pageable) { if (StringUtils.isEmpty(keyword)) { return new Page<Product>(); } if (pageable == null) { pageable = new Pageable(); } try { String text = QueryParser.escape(keyword); TermQuery snQuery = new TermQuery(new Term("sn", text)); Query keywordQuery = new QueryParser(Version.LUCENE_35, "keyword", new IKAnalyzer()).parse(text); QueryParser nameParser = new QueryParser(Version.LUCENE_35, "name", new IKAnalyzer()); nameParser.setDefaultOperator(QueryParser.AND_OPERATOR); Query nameQuery = nameParser.parse(text); FuzzyQuery nameFuzzyQuery = new FuzzyQuery(new Term("name", text), FUZZY_QUERY_MINIMUM_SIMILARITY); TermQuery introductionQuery = new TermQuery(new Term("introduction", text)); TermQuery isMarketableQuery = new TermQuery(new Term("isMarketable", "true")); TermQuery isListQuery = new TermQuery(new Term("isList", "true")); TermQuery isGiftQuery = new TermQuery(new Term("isGift", "false")); BooleanQuery textQuery = new BooleanQuery(); BooleanQuery query = new BooleanQuery(); textQuery.add(snQuery, Occur.SHOULD); textQuery.add(keywordQuery, Occur.SHOULD); textQuery.add(nameQuery, Occur.SHOULD); textQuery.add(nameFuzzyQuery, Occur.SHOULD); textQuery.add(introductionQuery, Occur.SHOULD); query.add(isMarketableQuery, Occur.MUST); query.add(isListQuery, Occur.MUST); query.add(isGiftQuery, Occur.MUST); query.add(textQuery, Occur.MUST); if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) { BigDecimal temp = startPrice; startPrice = endPrice; endPrice = temp; } if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0 && endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", startPrice.doubleValue(), endPrice.doubleValue(), true, true); query.add(numericRangeQuery, Occur.MUST); } else if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", startPrice.doubleValue(), null, true, false); query.add(numericRangeQuery, Occur.MUST); } else if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) { NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", null, endPrice.doubleValue(), false, true); query.add(numericRangeQuery, Occur.MUST); } FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Product.class); SortField[] sortFields = null; if (orderType == OrderType.priceAsc) { sortFields = new SortField[] { new SortField("price", SortField.DOUBLE, false), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.priceDesc) { sortFields = new SortField[] { new SortField("price", SortField.DOUBLE, true), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.salesDesc) { sortFields = new SortField[] { new SortField("sales", SortField.INT, true), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.scoreDesc) { sortFields = new SortField[] { new SortField("score", SortField.INT, true), new SortField("createDate", SortField.LONG, true) }; } else if (orderType == OrderType.dateDesc) { sortFields = new SortField[] { new SortField("createDate", SortField.LONG, true) }; } else { sortFields = new SortField[] { new SortField("isTop", SortField.STRING, true), new SortField(null, SortField.SCORE), new SortField("modifyDate", SortField.LONG, true) }; } fullTextQuery.setSort(new Sort(sortFields)); fullTextQuery.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize()); fullTextQuery.setMaxResults(pageable.getPageSize()); return new Page<Product>(fullTextQuery.getResultList(), fullTextQuery.getResultSize(), pageable); } catch (Exception e) { e.printStackTrace(); } return new Page<Product>(); }
From source file:net.cbtltd.rest.AbstractReservation.java
private static Double round(double unrounded, int precision, int roundingMode) { BigDecimal bd = new BigDecimal(unrounded); BigDecimal rounded = bd.setScale(precision, roundingMode); return rounded.doubleValue(); }
From source file:com.willwinder.universalgcodesender.MainWindow.java
private double getStepSize() { try {/*from w w w. j a va 2s . c o m*/ this.stepSizeSpinner.commitEdit(); } catch (ParseException e) { this.stepSizeSpinner.setValue(0.0); } BigDecimal bd = new BigDecimal(this.stepSizeSpinner.getValue().toString()).setScale(3, RoundingMode.HALF_EVEN); return bd.doubleValue(); //return Double.parseDouble( this.stepSizeSpinner.getValue().toString() ); }
From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java
private void insertFees(final LockHandler lockHandler, final Transfer transfer, final boolean forced, final BigDecimal originalAmount, final boolean simulation, final Set<ChargedFee> chargedFees) { final TransferType transferType = transfer.getType(); final Account from = transfer.getFrom(); final Account to = transfer.getTo(); final TransactionFeeQuery query = new TransactionFeeQuery(); query.setTransferType(transferType); final List<? extends TransactionFee> fees = transactionFeeService.search(query); BigDecimal totalPercentage = BigDecimal.ZERO; BigDecimal feeTotalAmount = BigDecimal.ZERO; Transfer topMost = getTopMost(transfer); final Calendar date = topMost.getDate(); transfer.setChildren(new ArrayList<Transfer>()); for (final TransactionFee fee : fees) { final Account fromAccount = fetchService.fetch(from, Account.Relationships.TYPE, MemberAccount.Relationships.MEMBER); final Account toAccount = fetchService.fetch(to, Account.Relationships.TYPE, MemberAccount.Relationships.MEMBER); final ChargedFee key = new ChargedFee(fee, fromAccount, toAccount); if (chargedFees.contains(key)) { throw new ValidationException("payment.error.circularFees"); }//www .j ava2 s.co m chargedFees.add(key); // Build the fee transfer final BuildTransferWithFeesDTO params = new BuildTransferWithFeesDTO(date, fromAccount, toAccount, originalAmount, fee, false); // rate stuff; buildTransfer MUST have these set. params.setEmissionDate(transfer.getEmissionDate()); params.setExpirationDate(transfer.getExpirationDate()); final Transfer feeTransfer = transactionFeeService.buildTransfer(params); // If the fee transfer is null, the fee should not be applied if (feeTransfer == null) { continue; } // Ensure the last fee when 100% will be the exact amount left if (fee instanceof SimpleTransactionFee && fee.getAmount().isPercentage()) { final BigDecimal feeValue = fee.getAmount().getValue(); // Only when it's not a single fee if (!(totalPercentage.equals(BigDecimal.ZERO) && feeValue.doubleValue() == 100.0)) { totalPercentage = totalPercentage.add(feeValue); // TODO: shouldn't this be >= 0 in stead of == 0 (Rinke) ? if (totalPercentage.compareTo(new BigDecimal(100)) == 0 && feeTransfer != null) { feeTransfer.setAmount(originalAmount.subtract(feeTotalAmount)); } } } // Insert the fee transfer if (feeTransfer != null && feeTransfer.getAmount().floatValue() > PRECISION_DELTA) { feeTotalAmount = feeTotalAmount.add(feeTransfer.getAmount()); feeTransfer.setParent(transfer); feeTransfer.setDate(transfer.getDate()); feeTransfer.setStatus(transfer.getStatus()); feeTransfer.setNextAuthorizationLevel(transfer.getNextAuthorizationLevel()); feeTransfer.setProcessDate(transfer.getProcessDate()); feeTransfer.setExternalTransfer(transfer.getExternalTransfer()); feeTransfer.setBy(transfer.getBy()); // Copy custom values of common custom fields from the parent to the fee transfer final List<PaymentCustomField> customFields = paymentCustomFieldService.list(feeTransfer.getType(), false); if (!CollectionUtils.isEmpty(transfer.getCustomValues())) { final Collection<PaymentCustomFieldValue> feeTransferCustomValues = new ArrayList<PaymentCustomFieldValue>(); for (final PaymentCustomFieldValue fieldValue : transfer.getCustomValues()) { final CustomField field = fieldValue.getField(); if (customFields.contains(field)) { final PaymentCustomFieldValue newFieldValue = new PaymentCustomFieldValue(); newFieldValue.setField(field); newFieldValue.setValue(fieldValue.getValue()); feeTransferCustomValues.add(newFieldValue); } } feeTransfer.setCustomValues(feeTransferCustomValues); } insertTransferAndPayFees(lockHandler, feeTransfer, forced, simulation, chargedFees); transfer.getChildren().add(feeTransfer); } } }
From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java
@Override @SuppressWarnings("unchecked") public void sube(byte[] datos, Usuario usuario, OutputStream out, Integer codigoInicial) { Date inicio = new Date(); int idx = 5;/* w ww.j ava2 s. c om*/ int i = 0; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy"); SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yy"); MathContext mc = new MathContext(16, RoundingMode.HALF_UP); NumberFormat nf = NumberFormat.getInstance(); nf.setGroupingUsed(false); nf.setMaximumFractionDigits(0); nf.setMinimumIntegerDigits(5); Transaction tx = null; try { String ejercicioId = "001-2012"; Map<String, CentroCosto> centrosDeCosto = new HashMap<>(); Map<String, TipoActivo> tipos = new HashMap<>(); Query tipoActivoQuery = currentSession() .createQuery("select ta from TipoActivo ta " + "where ta.empresa.id = :empresaId " + "and ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId " + "and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId"); log.debug("empresaId: {}", usuario.getEmpresa().getId()); log.debug("ejercicioId: {}", ejercicioId); log.debug("organizacionId: {}", usuario.getEmpresa().getOrganizacion().getId()); tipoActivoQuery.setLong("empresaId", usuario.getEmpresa().getId()); tipoActivoQuery.setString("ejercicioId", ejercicioId); tipoActivoQuery.setLong("organizacionId", usuario.getEmpresa().getOrganizacion().getId()); List<TipoActivo> listaTipos = tipoActivoQuery.list(); for (TipoActivo tipoActivo : listaTipos) { tipos.put(tipoActivo.getCuenta().getId().getIdCtaMayor(), tipoActivo); } log.debug("TIPOS: {}", tipos); Query proveedorQuery = currentSession().createQuery( "select p from Proveedor p where p.empresa.id = :empresaId and p.nombre = :nombreEmpresa"); proveedorQuery.setLong("empresaId", usuario.getEmpresa().getId()); proveedorQuery.setString("nombreEmpresa", usuario.getEmpresa().getNombre()); Proveedor proveedor = (Proveedor) proveedorQuery.uniqueResult(); Query codigoDuplicadoQuery = currentSession() .createQuery("select a from Activo a where a.empresa.id = :empresaId and a.codigo = :codigo"); XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(datos)); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet ccostoFantasma = wb.createSheet("CCOSTO-FANTASMAS"); int ccostoFantasmaRow = 0; XSSFSheet sinCCosto = wb.createSheet("SIN-CCOSTO"); int sinCCostoRow = 0; XSSFSheet codigoAsignado = wb.createSheet("CODIGO-ASIGNADO"); int codigoAsignadoRow = 0; XSSFSheet fechaInvalida = wb.createSheet("FECHA-INVALIDA"); int fechaInvalidaRow = 0; XSSFSheet sinCosto = wb.createSheet("SIN-COSTO"); int sinCostoRow = 0; tx = currentSession().beginTransaction(); for (idx = 0; idx <= 5; idx++) { XSSFSheet sheet = workbook.getSheetAt(idx); int rows = sheet.getPhysicalNumberOfRows(); for (i = 2; i < rows; i++) { log.debug("Leyendo pagina {} renglon {}", idx, i); XSSFRow row = sheet.getRow(i); if (row.getCell(0) == null) { break; } String nombreGrupo = row.getCell(0).getStringCellValue().trim(); TipoActivo tipoActivo = tipos.get(nombreGrupo); if (tipoActivo != null) { String cuentaCCosto = row.getCell(2).toString().trim(); if (StringUtils.isNotBlank(cuentaCCosto)) { CentroCosto centroCosto = centrosDeCosto.get(cuentaCCosto); if (centroCosto == null) { Query ccostoQuery = currentSession().createQuery("select cc from CentroCosto cc " + "where cc.id.ejercicio.id.idEjercicio = :ejercicioId " + "and cc.id.ejercicio.id.organizacion.id = :organizacionId " + "and cc.id.idCosto like :idCosto"); ccostoQuery.setString("ejercicioId", ejercicioId); ccostoQuery.setLong("organizacionId", usuario.getEmpresa().getOrganizacion().getId()); ccostoQuery.setString("idCosto", "1.01." + cuentaCCosto); ccostoQuery.setMaxResults(1); List<CentroCosto> listaCCosto = ccostoQuery.list(); if (listaCCosto != null && listaCCosto.size() > 0) { centroCosto = listaCCosto.get(0); } if (centroCosto == null) { XSSFRow renglon = ccostoFantasma.createRow(ccostoFantasmaRow++); renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1)); renglon.createCell(1).setCellValue(row.getCell(0).toString()); renglon.createCell(2).setCellValue(row.getCell(1).toString()); renglon.createCell(3).setCellValue(row.getCell(2).toString()); renglon.createCell(4).setCellValue(row.getCell(3).toString()); renglon.createCell(5).setCellValue(row.getCell(4).toString()); renglon.createCell(6).setCellValue(row.getCell(5).toString()); renglon.createCell(7).setCellValue(row.getCell(6).toString()); renglon.createCell(8).setCellValue(row.getCell(7).toString()); renglon.createCell(9).setCellValue(row.getCell(8).toString()); renglon.createCell(10).setCellValue(row.getCell(9).toString()); renglon.createCell(11).setCellValue(row.getCell(10).toString()); renglon.createCell(12).setCellValue(row.getCell(11).toString()); renglon.createCell(13).setCellValue(row.getCell(12).toString()); renglon.createCell(14).setCellValue(row.getCell(13).toString()); renglon.createCell(15).setCellValue(row.getCell(14).toString()); renglon.createCell(16).setCellValue(row.getCell(15).toString()); continue; } centrosDeCosto.put(cuentaCCosto, centroCosto); } String poliza = null; switch (row.getCell(4).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: poliza = row.getCell(4).toString(); poliza = StringUtils.removeEnd(poliza, ".0"); log.debug("POLIZA-N: {}", poliza); break; case XSSFCell.CELL_TYPE_STRING: poliza = row.getCell(4).getStringCellValue().trim(); log.debug("POLIZA-S: {}", poliza); break; } Boolean seguro = false; if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) { seguro = true; } Boolean garantia = false; if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) { garantia = true; } Date fechaCompra = null; if (row.getCell(7) != null) { log.debug("VALIDANDO FECHA"); XSSFCell cell = row.getCell(7); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: log.debug("ES NUMERIC"); if (DateUtil.isCellDateFormatted(cell)) { log.debug("ES FECHA"); fechaCompra = cell.getDateCellValue(); } else if (DateUtil.isCellInternalDateFormatted(cell)) { log.debug("ES FECHA INTERNAL"); fechaCompra = cell.getDateCellValue(); } else { BigDecimal bd = new BigDecimal(cell.getNumericCellValue()); bd = stripTrailingZeros(bd); log.debug("CONVIRTIENDO DOUBLE {} - {}", DateUtil.isValidExcelDate(bd.doubleValue()), bd); fechaCompra = HSSFDateUtil.getJavaDate(bd.longValue(), true); log.debug("Cal: {}", fechaCompra); } break; case Cell.CELL_TYPE_FORMULA: log.debug("ES FORMULA"); CellValue cellValue = evaluator.evaluate(cell); switch (cellValue.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { fechaCompra = DateUtil.getJavaDate(cellValue.getNumberValue(), true); } } } } if (row.getCell(7) != null && fechaCompra == null) { String fechaCompraString; if (row.getCell(7).getCellType() == Cell.CELL_TYPE_STRING) { fechaCompraString = row.getCell(7).getStringCellValue(); } else { fechaCompraString = row.getCell(7).toString().trim(); } try { fechaCompra = sdf.parse(fechaCompraString); } catch (ParseException e) { try { fechaCompra = sdf2.parse(fechaCompraString); } catch (ParseException e2) { try { fechaCompra = sdf3.parse(fechaCompraString); } catch (ParseException e3) { // no se pudo convertir } } } } if (fechaCompra == null) { XSSFRow renglon = fechaInvalida.createRow(fechaInvalidaRow++); renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1)); renglon.createCell(1).setCellValue(row.getCell(0).toString()); renglon.createCell(2).setCellValue(row.getCell(1).toString()); renglon.createCell(3).setCellValue(row.getCell(2).toString()); renglon.createCell(4).setCellValue(row.getCell(3).toString()); renglon.createCell(5).setCellValue(row.getCell(4).toString()); renglon.createCell(6).setCellValue(row.getCell(5).toString()); renglon.createCell(7).setCellValue(row.getCell(6).toString()); renglon.createCell(8).setCellValue(row.getCell(7).toString()); renglon.createCell(9).setCellValue(row.getCell(8).toString()); renglon.createCell(10).setCellValue(row.getCell(9).toString()); renglon.createCell(11).setCellValue(row.getCell(10).toString()); renglon.createCell(12).setCellValue(row.getCell(11).toString()); renglon.createCell(13).setCellValue(row.getCell(12).toString()); renglon.createCell(14).setCellValue(row.getCell(13).toString()); renglon.createCell(15).setCellValue(row.getCell(14).toString()); renglon.createCell(16).setCellValue(row.getCell(15).toString()); continue; } String codigo = null; switch (row.getCell(8).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: codigo = row.getCell(8).toString(); break; case XSSFCell.CELL_TYPE_STRING: codigo = row.getCell(8).getStringCellValue().trim(); break; } if (StringUtils.isBlank(codigo)) { codigo = nf.format(codigoInicial); XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++); renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1)); renglon.createCell(1).setCellValue(row.getCell(0).toString()); renglon.createCell(2).setCellValue(row.getCell(1).toString()); renglon.createCell(3).setCellValue(row.getCell(2).toString()); renglon.createCell(4).setCellValue(row.getCell(3).toString()); renglon.createCell(5).setCellValue(row.getCell(4).toString()); renglon.createCell(6).setCellValue(row.getCell(5).toString()); renglon.createCell(7).setCellValue(row.getCell(6).toString()); renglon.createCell(8).setCellValue(row.getCell(7).toString()); renglon.createCell(9).setCellValue(codigoInicial); renglon.createCell(10).setCellValue(row.getCell(9).toString()); renglon.createCell(11).setCellValue(row.getCell(10).toString()); renglon.createCell(12).setCellValue(row.getCell(11).toString()); renglon.createCell(13).setCellValue(row.getCell(12).toString()); renglon.createCell(14).setCellValue(row.getCell(13).toString()); renglon.createCell(15).setCellValue(row.getCell(14).toString()); renglon.createCell(16).setCellValue(row.getCell(15).toString()); codigoInicial++; } else { // busca codigo duplicado if (codigo.contains(".")) { codigo = codigo.substring(0, codigo.lastIndexOf(".")); log.debug("CODIGO: {}", codigo); } codigoDuplicadoQuery.setLong("empresaId", usuario.getEmpresa().getId()); codigoDuplicadoQuery.setString("codigo", codigo); Activo activo = (Activo) codigoDuplicadoQuery.uniqueResult(); if (activo != null) { XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++); renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1)); renglon.createCell(1).setCellValue(row.getCell(0).toString()); renglon.createCell(2).setCellValue(row.getCell(1).toString()); renglon.createCell(3).setCellValue(row.getCell(2).toString()); renglon.createCell(4).setCellValue(row.getCell(3).toString()); renglon.createCell(5).setCellValue(row.getCell(4).toString()); renglon.createCell(6).setCellValue(row.getCell(5).toString()); renglon.createCell(7).setCellValue(row.getCell(6).toString()); renglon.createCell(8).setCellValue(row.getCell(7).toString()); renglon.createCell(9).setCellValue(codigo + "-" + nf.format(codigoInicial)); renglon.createCell(10).setCellValue(row.getCell(9).toString()); renglon.createCell(11).setCellValue(row.getCell(10).toString()); renglon.createCell(12).setCellValue(row.getCell(11).toString()); renglon.createCell(13).setCellValue(row.getCell(12).toString()); renglon.createCell(14).setCellValue(row.getCell(13).toString()); renglon.createCell(15).setCellValue(row.getCell(14).toString()); renglon.createCell(16).setCellValue(row.getCell(15).toString()); codigo = nf.format(codigoInicial); codigoInicial++; } } String descripcion = null; if (row.getCell(9) != null) { switch (row.getCell(9).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: descripcion = row.getCell(9).toString(); descripcion = StringUtils.removeEnd(descripcion, ".0"); break; case XSSFCell.CELL_TYPE_STRING: descripcion = row.getCell(9).getStringCellValue().trim(); break; default: descripcion = row.getCell(9).toString().trim(); } } String marca = null; if (row.getCell(10) != null) { switch (row.getCell(10).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: marca = row.getCell(10).toString(); marca = StringUtils.removeEnd(marca, ".0"); break; case XSSFCell.CELL_TYPE_STRING: marca = row.getCell(10).getStringCellValue().trim(); break; default: marca = row.getCell(10).toString().trim(); } } String modelo = null; if (row.getCell(11) != null) { switch (row.getCell(11).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: modelo = row.getCell(11).toString(); modelo = StringUtils.removeEnd(modelo, ".0"); break; case XSSFCell.CELL_TYPE_STRING: modelo = row.getCell(11).getStringCellValue().trim(); break; default: modelo = row.getCell(11).toString().trim(); } } String serie = null; if (row.getCell(12) != null) { switch (row.getCell(12).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: serie = row.getCell(12).toString(); serie = StringUtils.removeEnd(serie, ".0"); break; case XSSFCell.CELL_TYPE_STRING: serie = row.getCell(12).getStringCellValue().trim(); break; default: serie = row.getCell(12).toString().trim(); } } String responsable = null; if (row.getCell(13) != null) { switch (row.getCell(13).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: responsable = row.getCell(13).toString(); responsable = StringUtils.removeEnd(responsable, ".0"); break; case XSSFCell.CELL_TYPE_STRING: responsable = row.getCell(13).getStringCellValue().trim(); break; default: responsable = row.getCell(13).toString().trim(); } } String ubicacion = null; if (row.getCell(14) != null) { switch (row.getCell(14).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: ubicacion = row.getCell(14).toString(); ubicacion = StringUtils.removeEnd(ubicacion, ".0"); break; case XSSFCell.CELL_TYPE_STRING: ubicacion = row.getCell(14).getStringCellValue().trim(); break; default: ubicacion = row.getCell(14).toString().trim(); } } BigDecimal costo = null; switch (row.getCell(15).getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: costo = new BigDecimal(row.getCell(15).getNumericCellValue(), mc); log.debug("COSTO-N: {} - {}", costo, row.getCell(15).getNumericCellValue()); break; case XSSFCell.CELL_TYPE_STRING: costo = new BigDecimal(row.getCell(15).toString(), mc); log.debug("COSTO-S: {} - {}", costo, row.getCell(15).toString()); break; case XSSFCell.CELL_TYPE_FORMULA: costo = new BigDecimal( evaluator.evaluateInCell(row.getCell(15)).getNumericCellValue(), mc); log.debug("COSTO-F: {}", costo); } if (costo == null) { XSSFRow renglon = sinCosto.createRow(sinCostoRow++); renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1)); renglon.createCell(1).setCellValue(row.getCell(0).toString()); renglon.createCell(2).setCellValue(row.getCell(1).toString()); renglon.createCell(3).setCellValue(row.getCell(2).toString()); renglon.createCell(4).setCellValue(row.getCell(3).toString()); renglon.createCell(5).setCellValue(row.getCell(4).toString()); renglon.createCell(6).setCellValue(row.getCell(5).toString()); renglon.createCell(7).setCellValue(row.getCell(6).toString()); renglon.createCell(8).setCellValue(row.getCell(7).toString()); renglon.createCell(9).setCellValue(row.getCell(8).toString()); renglon.createCell(10).setCellValue(row.getCell(9).toString()); renglon.createCell(11).setCellValue(row.getCell(10).toString()); renglon.createCell(12).setCellValue(row.getCell(11).toString()); renglon.createCell(13).setCellValue(row.getCell(12).toString()); renglon.createCell(14).setCellValue(row.getCell(13).toString()); renglon.createCell(15).setCellValue(row.getCell(14).toString()); renglon.createCell(16).setCellValue(row.getCell(15).toString()); continue; } Activo activo = new Activo(fechaCompra, seguro, garantia, poliza, codigo, descripcion, marca, modelo, serie, responsable, ubicacion, costo, tipoActivo, centroCosto, proveedor, usuario.getEmpresa()); this.crea(activo, usuario); } else { XSSFRow renglon = sinCCosto.createRow(sinCCostoRow++); renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1)); renglon.createCell(1).setCellValue(row.getCell(0).toString()); renglon.createCell(2).setCellValue(row.getCell(1).toString()); renglon.createCell(3).setCellValue(row.getCell(2).toString()); renglon.createCell(4).setCellValue(row.getCell(3).toString()); renglon.createCell(5).setCellValue(row.getCell(4).toString()); renglon.createCell(6).setCellValue(row.getCell(5).toString()); renglon.createCell(7).setCellValue(row.getCell(6).toString()); renglon.createCell(8).setCellValue(row.getCell(7).toString()); renglon.createCell(9).setCellValue(row.getCell(8).toString()); renglon.createCell(10).setCellValue(row.getCell(9).toString()); renglon.createCell(11).setCellValue(row.getCell(10).toString()); renglon.createCell(12).setCellValue(row.getCell(11).toString()); renglon.createCell(13).setCellValue(row.getCell(12).toString()); renglon.createCell(14).setCellValue(row.getCell(13).toString()); renglon.createCell(15).setCellValue(row.getCell(14).toString()); renglon.createCell(16).setCellValue(row.getCell(15).toString()); continue; } } else { throw new RuntimeException( "(" + idx + ":" + i + ") No se encontro el tipo de activo " + nombreGrupo); } } } tx.commit(); log.debug("################################################"); log.debug("################################################"); log.debug("TERMINO EN {} MINS", (new Date().getTime() - inicio.getTime()) / (1000 * 60)); log.debug("################################################"); log.debug("################################################"); wb.write(out); } catch (IOException | RuntimeException e) { if (tx != null && tx.isActive()) { tx.rollback(); } log.error("Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e); throw new RuntimeException( "Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e); } }
From source file:axiom.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet.//from w w w. j av a 2 s. 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(); for (int i = 0; i < columns.length; i++) { // set prototype? if (columns[i].isPrototypeField()) { protoName = rs.getString(i + 1 + offset); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError(ErrorReporter.errorMsg(this.getClass(), "createNode") + "Invalid prototype name: " + protoName + " - using default"); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(i + 1 + offset); // 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(i + 1 + offset); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: newprop.setBooleanValue(rs.getBoolean(i + 1 + offset)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(i + 1 + offset)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(i + 1 + offset)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(i + 1 + offset); 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.setStringValue(rs.getString(i+1+offset)); newprop.setJavaObjectValue(rs.getBytes(i + 1 + offset)); break; case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(i + 1 + offset); 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(i + 1 + offset)); } catch (SQLException x) { Reader in = rs.getCharacterStream(i + 1 + offset); char[] buffer = new char[2048]; int read = 0; int r; while ((r = in.read(buffer, read, buffer.length - read)) > -1) { read += r; if (read == buffer.length) { // grow input buffer char[] newBuffer = new char[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); buffer = newBuffer; } } newprop.setStringValue(new String(buffer, 0, read)); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(i + 1 + offset)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(i + 1 + offset)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(i + 1 + offset); 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(i + 1 + offset)); 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; } 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.reftype == Relation.PRIMITIVE || rel.reftype == Relation.REFERENCE)) { 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.reftype == Relation.REFERENCE) && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel.otherType, this.app.getCurrentRequestEvaluator().getLayer()); } propMap.put(rel.propName.toLowerCase(), prop); } } node.init(dbmap, id, name, protoName, propMap, safe); return node; }
From source file:er.extensions.appserver.ERXApplication.java
protected boolean checkMemory(BigDecimal memoryThreshold, boolean attemptGC) { boolean pastThreshold = false; if (memoryThreshold != null) { long max = Runtime.getRuntime().maxMemory(); long total = Runtime.getRuntime().totalMemory(); long free = Runtime.getRuntime().freeMemory() + (max - total); long used = max - free; long starvedThreshold = (long) (memoryThreshold.doubleValue() < 1.0 ? memoryThreshold.doubleValue() * max : (max - (memoryThreshold.doubleValue() * 1024 * 1024))); synchronized (this) { long time = System.currentTimeMillis(); if (attemptGC && (used > starvedThreshold) && (time > _lastGC + 60 * 1000L)) { _lastGC = time;//from www. ja va 2s. c o m Runtime.getRuntime().gc(); max = Runtime.getRuntime().maxMemory(); total = Runtime.getRuntime().totalMemory(); free = Runtime.getRuntime().freeMemory() + (max - total); used = max - free; } pastThreshold = (used > starvedThreshold); } } return pastThreshold; }