List of usage examples for java.math BigDecimal ZERO
BigDecimal ZERO
To view the source code for java.math BigDecimal ZERO.
Click Source Link
From source file:com.ocs.dynamo.ui.composite.table.CustomTreeTable.java
@Override public void build() { setEditable(true);/* w w w .ja v a 2 s . c o m*/ setSizeFull(); // retrieve the rows to display final List<V> parentCollection = getParentCollection(); addContainerProperties(); int nrOfProperties = getContainerPropertyIds().size(); String[] sumColumns = getSumColumns(); // adds a style generator that highlights the parent rows in bold setCellStyleGenerator(new CellStyleGenerator() { @Override public String getStyle(Table source, Object itemId, Object propertyId) { if (itemId.toString().startsWith(PREFIX_PARENTROW)) { return "parentRow"; } else { return getCustomStyle(itemId, propertyId); } } }); // custom field factory for creating editable fields for certain // properties this.setTableFieldFactory(new TableFieldFactory() { private boolean editAllowed = isEditAllowed(); @Override public Field<?> createField(Container container, Object itemId, final Object propertyId, Component uiContext) { if (!isViewMode() && editAllowed && isEditable(propertyId.toString()) && itemId.toString().startsWith(PREFIX_CHILDROW)) { final TextField tf = new TextField(); tf.setData(itemId); tf.setNullRepresentation(""); tf.setNullSettingAllowed(true); // set the appropriate converter tf.setConverter(createConverter(propertyId.toString())); tf.addFocusListener(new FocusListener() { @Override public void focus(FocusEvent event) { clickedColumn = propertyId.toString(); } }); // add a value change listener (for responding to paste // events and normal changes) tf.addValueChangeListener(new Property.ValueChangeListener() { @Override public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) { if (propagateChanges) { handleChange(tf, propertyId.toString(), (String) event.getProperty().getValue()); } } }); // align all text field to the right tf.setStyleName(DynamoConstants.CSS_NUMERICAL); postProcessField(propertyId, itemId, tf); return tf; } return null; } }); int parentCounter = 0; int childCounter = 0; // footer sums Map<String, BigDecimal> totalSumMap = new HashMap<>(); for (String s : sumColumns) { totalSumMap.put(s, BigDecimal.ZERO); } for (V v : parentCollection) { // sum on the parent level Map<String, BigDecimal> sumMap = new HashMap<>(); for (String s : sumColumns) { sumMap.put(s, BigDecimal.ZERO); } Object[] parentRow = new Object[nrOfProperties]; fillParentRow(parentRow, v); Object parentId = this.addItem(parentRow, PREFIX_PARENTROW + parentCounter); this.setChildrenAllowed(parentId, true); this.setCollapsed(parentId, false); List<U> rowCollection = getRowCollection(v); for (U u : rowCollection) { Object[] childRow = new Object[nrOfProperties]; fillChildRow(childRow, u, v); // add the child and set the connection to the parent Object childId = this.addItem(childRow, PREFIX_CHILDROW + childCounter); this.setParent(childId, parentId); this.setChildrenAllowed(childId, false); // update the sum columns on the parent level for (String column : sumColumns) { Number value = (Number) this.getItem(childId).getItemProperty(column).getValue(); BigDecimal sum = sumMap.get(column); sumMap.put(column, sum.add(value == null ? BigDecimal.ZERO : toBigDecimal(value))); } childCounter++; } // set the sum on the parent level and update the grand total for (String s : sumColumns) { BigDecimal sum = sumMap.get(s); this.getItem(parentId).getItemProperty(s).setValue(convertNumber(sum, s)); BigDecimal totalSum = totalSumMap.get(s); totalSumMap.put(s, totalSum.add(sum)); } parentCounter++; } // update the footer sums for (String column : sumColumns) { BigDecimal bd = totalSumMap.get(column); this.setColumnFooter(column, convertToString(bd, column)); } setFooterVisible(true); // right align certain columns for (Object propertyId : this.getContainerPropertyIds()) { if (isRightAligned(propertyId.toString())) { this.setColumnAlignment(propertyId, Table.Align.RIGHT); } } // respond to a click by storing the column ID this.addItemClickListener(new ItemClickListener() { @Override public void itemClick(ItemClickEvent event) { if (MouseButton.RIGHT.equals(event.getButton())) { clickedColumn = (String) event.getPropertyId(); } } }); if (isShowActionMenu()) { constructActionMenu(parentCollection); } }
From source file:br.com.webbudget.domain.model.service.LogbookService.java
/** * * @param refueling/*from ww w. jav a 2 s. c om*/ */ @Transactional public void saveRefueling(Refueling refueling) { if (!refueling.isFuelsValid()) { throw new InternalServiceError("error.refueling.invalid-fuels"); } // pega o ultimo odometro para calcular a distancia percorrida int lastOdometer = this.refuelingRepository.findLastOdometerForVehicle(refueling.getVehicle()); // calcula a distancia refueling.setFirstRefueling(lastOdometer == 0); refueling.calculateDistance(lastOdometer); // pegamos a lista dos abastecimentos nao contabilizados e reservamos final List<Refueling> unaccounteds = this.refuelingRepository .findUnaccountedsForVehicle(refueling.getVehicle()); // se nao e um tanque cheio, marcamos que sera contabilizado no proximo // tanque cheio, se for, contabiliza a media do tanque if (refueling.isFullTank()) { // montamos o valor do ultimo odometro com base nas parciais ou // com base no ultimo odometro registrado com tanque cheio if (!unaccounteds.isEmpty()) { final int totalDistance = unaccounteds.stream().mapToInt(Refueling::getDistance).sum() + refueling.getDistance(); // pega o total de litros utilizados final BigDecimal liters = unaccounteds.stream().map(Refueling::getLiters) .reduce(BigDecimal.ZERO, BigDecimal::add).add(refueling.getLiters()); // adiciona os litros atuais e manda calcular a media refueling.calculateAverageComsumption(totalDistance, liters); } else { refueling.calculateAverageComsumption(); } // seta os que nao estavam contabilizados como contabilizados unaccounteds.stream().forEach(unaccounted -> { unaccounted.setAccounted(true); unaccounted.setAccountedBy(refueling.getCode()); this.refuelingRepository.save(unaccounted); }); // marca o abastecimento atual como contabilizado refueling.setAccounted(true); } else { refueling.setAccounted(false); } // salvamos o abastecimento final Refueling saved = this.refuelingRepository.save(refueling); // salvamos os combustiveis refueling.getFuels().stream().forEach(fuel -> { fuel.setRefueling(saved); this.fuelRepository.save(fuel); }); // gerar o movimento financeiro final MovementBuilder builder = new MovementBuilder().withValue(saved.getCost()) .onDueDate(saved.getEventDate()).describedBy(saved.createMovementDescription()) .inThePeriodOf(saved.getFinancialPeriod()) .dividedAmong(new ApportionmentBuilder().onCostCenter(saved.getCostCenter()) .withMovementClass(saved.getMovementClass()).withValue(saved.getCost())); saved.setMovementCode(builder.getMovementCode()); // invoca inclusao do movimento this.createMovementEvent.fire(builder); // atualiza o codigo do movimento no abastecimento this.refuelingRepository.save(saved); final int lastVehicleOdometer = this.vehicleRepository.findLastOdometer(refueling.getVehicle()); // atualiza ou nao o odometro if (refueling.getOdometer() > lastVehicleOdometer) { refueling.updateVehicleOdometer(); this.vehicleRepository.save(refueling.getVehicle()); } }
From source file:com.gst.portfolio.shareaccounts.domain.ShareAccountCharge.java
public Money waive(final MonetaryCurrency currency) { Money amountWaivedToDate = Money.of(currency, this.amountWaived); Money amountOutstanding = Money.of(currency, this.amountOutstanding); this.amountWaived = amountWaivedToDate.plus(amountOutstanding).getAmount(); this.amountOutstanding = BigDecimal.ZERO; this.waived = true; return amountOutstanding; }
From source file:com.redhat.rhtracking.web.controller.ConsultantController.java
@RequestMapping(value = "/consultant/assignation", method = RequestMethod.GET) public String assignationView(@RequestParam(required = true) String id, @RequestParam(required = true) String type, Model model) { Map<String, Object> consultants = consultantService.listAllConsultants(new HashMap<String, Object>()); model.addAttribute("consultants", (List<Map<String, Object>>) consultants.get("list")); Map<String, Object> request = new HashMap<>(); request.put("identifier", id); Map<String, Object> opportunity = deliveryMatrixService.findOpportunityBy(request); model.addAllAttributes(opportunity); Map<String, Object> hours = deliveryMatrixService.findOpportunityHours(request); int hour = -1; BigDecimal maxPay = BigDecimal.ZERO; for (Map<String, Object> h : (List<Map<String, Object>>) hours.get("list")) { String ht = (String) h.get("hourType"); if (ht.equals(type.toUpperCase())) { logger.debug("found" + h); hour = (int) h.get("quantity") - (int) h.get("hoursToAccrued"); maxPay = (BigDecimal) h.get("unitPrice"); break; }/*from w ww . j ava2 s .co m*/ } model.addAttribute("hour", hour); model.addAttribute("maxPay", maxPay); model.addAttribute("hourType", type); return "/consultant/assignation"; }
From source file:de.appsolve.padelcampus.db.model.Player.java
public BigDecimal getBalance() { return balance == null ? BigDecimal.ZERO : balance; }
From source file:mx.edu.um.mateo.rh.dao.EmpleadoDaoTest.java
/** * Test of actualiza method, of class EmpleadoDao. *//*from w w w . j a va2s . c o m*/ @Test public void debieraActualizarEmpleado() { log.debug("Debiera actualizar empleado"); Organizacion organizacion = new Organizacion("tst-01", "test-01", "test-01"); currentSession().save(organizacion); Empresa empresa = new Empresa("tst-01", "test-01", "test-01", "000000000001", organizacion); currentSession().save(empresa); Rol rol = new Rol("ROLE_TEST"); currentSession().save(rol); Set<Rol> roles = new HashSet<>(); roles.add(rol); Almacen almacen = new Almacen("TST", "TEST", empresa); currentSession().save(almacen); Usuario usuario = new Usuario("bugs@um.edu.mx", "TEST-01", "TEST-01", "TEST-01"); usuario.setEmpresa(empresa); usuario.setAlmacen(almacen); usuario.setRoles(roles); currentSession().save(usuario); Long id = usuario.getId(); assertNotNull(id); Empleado empleado = new Empleado("test001", "test", "test", "test", "M", "address", "A", "curp", "rfc", "cuenta", "imss", 10, 100, BigDecimal.ZERO, "mo", "ife", "ra", Boolean.TRUE, "padre", "madre", "C", "Conyugue", Boolean.TRUE, Boolean.TRUE, "iglesia", "responsabilidad", empresa); instance.graba(empleado); assertNotNull(empleado); assertNotNull(empleado.getId()); assertEquals("test", empleado.getNombre()); empleado.setNombre("PRUEBA"); instance.graba(empleado, usuario); Empleado prueba = instance.obtiene(empleado.getId()); assertNotNull(prueba); assertEquals("PRUEBA", prueba.getNombre()); }
From source file:com.jeans.iservlet.service.asset.impl.AssetServiceImpl.java
@Override @Transactional/*from w w w.ja v a 2 s .c o m*/ public int saveProps(Set<Long> ids, byte type, Map<String, Object> props) { if (ids.isEmpty()) { return 0; } if (ids.size() == 1) { Asset asset = loadAsset(ids.iterator().next(), type); if (null == asset) { return 0; } /* * ? ?? null?null -99???? ? */ asset.setName((String) props.get("name")); asset.setVendor((String) props.get("vendor")); asset.setModelOrVersion((String) props.get("modelOrVersion")); asset.setAssetUsage((String) props.get("assetUsage")); asset.setPurchaseTime((Date) props.get("purchaseTime")); int q = (int) props.get("quantity"); asset.setQuantity(q < 0 ? 1 : q); BigDecimal c = (BigDecimal) props.get("cost"); asset.setCost(c.compareTo(BigDecimal.ZERO) == -1 ? BigDecimal.ZERO : c); asset.setComment((String) props.get("comment")); if (asset instanceof Hardware) { ((Hardware) asset).setCode((String) props.get("code")); ((Hardware) asset).setFinancialCode((String) props.get("financialCode")); ((Hardware) asset).setSn((String) props.get("sn")); ((Hardware) asset).setConfiguration((String) props.get("configuration")); byte w = (byte) props.get("warranty"); if (w >= -1 && w <= 1) { ((Hardware) asset).setWarranty(w); } ((Hardware) asset).setLocation((String) props.get("location")); ((Hardware) asset).setIp((String) props.get("ip")); byte i = (byte) props.get("importance"); if (i >= 0 && i <= 2) { ((Hardware) asset).setImportance(i); } hwDao.update((Hardware) asset); return 1; } else if (asset instanceof Software) { byte s = (byte) props.get("softwareType"); if (s >= 0 && s <= 6) { ((Software) asset).setSoftwareType(s); } ((Software) asset).setLicense((String) props.get("license")); ((Software) asset).setExpiredTime((Date) props.get("expiredTime")); swDao.update((Software) asset); return 1; } else { return 0; } } else { List<Asset> assets = loadAssets(ids, type); int count = assets.size(); for (Asset asset : assets) { /* * ????? null????? -99????? ????? */ String v = (String) props.get("name"); if (!StringUtils.isEmpty(v)) { asset.setName(v); } v = (String) props.get("vendor"); if (!StringUtils.isEmpty(v)) { asset.setVendor(v); } v = (String) props.get("modelOrVersion"); if (!StringUtils.isEmpty(v)) { asset.setModelOrVersion(v); } v = (String) props.get("assetUsage"); if (!StringUtils.isEmpty(v)) { asset.setAssetUsage(v); } Date d = (Date) props.get("purchaseTime"); if (null != d) { asset.setPurchaseTime(d); } int q = (int) props.get("quantity"); if (q >= 0) { asset.setQuantity(q); } BigDecimal c = (BigDecimal) props.get("cost"); if (c.compareTo(BigDecimal.ZERO) != -1) { asset.setCost(c); } v = (String) props.get("comment"); if (!StringUtils.isEmpty(v)) { asset.setComment(v); } if (asset instanceof Hardware) { v = (String) props.get("sn"); if (!StringUtils.isEmpty(v)) { ((Hardware) asset).setSn(v); } v = (String) props.get("configuration"); if (!StringUtils.isEmpty(v)) { ((Hardware) asset).setConfiguration(v); } byte w = (byte) props.get("warranty"); if (w >= -1 && w <= 1) { ((Hardware) asset).setWarranty(w); } v = (String) props.get("location"); if (!StringUtils.isEmpty(v)) { ((Hardware) asset).setLocation(v); } v = (String) props.get("ip"); if (!StringUtils.isEmpty(v)) { ((Hardware) asset).setIp(v); } byte i = (byte) props.get("importance"); if (i >= 0 && i <= 2) { ((Hardware) asset).setImportance(i); } hwDao.update((Hardware) asset); } else if (asset instanceof Software) { byte s = (byte) props.get("softwareType"); if (s >= 0 && s <= 6) { ((Software) asset).setSoftwareType(s); } v = (String) props.get("license"); if (!StringUtils.isEmpty(v)) { ((Software) asset).setLicense(v); } d = (Date) props.get("expiredTime"); if (null != d) { ((Software) asset).setExpiredTime(d); } swDao.update((Software) asset); } else { count--; } } return count; } }
From source file:com.axelor.apps.account.service.MoveLineExportService.java
public BigDecimal getSumDebit(String queryFilter, List<? extends Move> moveList) { Query q = JPA.em().createQuery("select SUM(self.debit) FROM MoveLine as self WHERE " + queryFilter, BigDecimal.class); q.setParameter(1, moveList);//from w ww .ja va 2s .c o m BigDecimal result = (BigDecimal) q.getSingleResult(); log.debug("Total debit : {}", result); if (result != null) { return result; } else { return BigDecimal.ZERO; } }
From source file:com.SCI.centraltoko.utility.UtilityTools.java
public static BigDecimal parseNumberToBigDecimal(String text) { if (!StringUtils.hasText(text)) return BigDecimal.ZERO; try {/*from ww w . j a v a 2s . c om*/ BigDecimal number = new BigDecimal(NumberFormat.getInstance().parse(text).doubleValue()); return number; } catch (ParseException ex) { if (Locale.US == Locale.getDefault()) { JOptionPane.showMessageDialog(null, "Region setting anda menggunakan US, pemisah ribuan adalah .(titik) dan pemisah pecahan ada;ah ,(koma) "); } else if (Locale.getDefault().getCountry().equalsIgnoreCase("INDONESIA") && Locale.getDefault().getLanguage().equalsIgnoreCase("ID")) { JOptionPane.showMessageDialog(null, "Region setting anda menggunakan Indonesia, pemisah ribuan adalah ,(koma) dan pemisah pecahan adalah .(titik)"); } } return null; }
From source file:com.qcadoo.mes.productionPerShift.dataProvider.ProductionPerShiftDataProvider.java
/** * Returns sum of quantities from matching daily shift progress entries. Notice that corrected quantities take precedence over * planned ones (see documentation for #findIdsOfEffectiveProgressForDay).<br/> * <br/>/* w w w . jav a2s .co m*/ * * By default this method counts quantities for each operations in technology tree. If you want to count only quantities for * root operations pass ProductionPerShiftDataProvider#ONLY_ROOT_OPERATIONS_CRITERIA search criterion as a second argument. * * @param technologyId * id of technology * @param additionalCriteria * optional additional criteria. * @return sum of quantities from matching daily shift progresses or BigDecimal#ZERO if there is no matching progress entries. * @since 1.3.0 */ public BigDecimal countSumOfQuantities(final Long technologyId, final SearchCriterion additionalCriteria) { Set<Long> pfdIds = findIdsOfEffectiveProgressForDay(technologyId); if (pfdIds.isEmpty()) { return BigDecimal.ZERO; } SearchProjectionList projectionList = list(); projectionList.add( alias(sum(DAILY_PROGRESS_ALIAS + DOT + DailyProgressFields.QUANTITY), QUANTITY_SUM_PROJECTION)); // To prevent NPE during conversion to generic entity projectionList.add(rowCount()); SearchCriteriaBuilder scb = getDailyProgressDD().findWithAlias(DAILY_PROGRESS_ALIAS); scb.setProjection(projectionList); scb.createAlias(DAILY_PROGRESS_ALIAS + DOT + DailyProgressFields.PROGRESS_FOR_DAY, PROGRESS_FOR_DAY_ALIAS, JoinType.INNER); scb.createAlias(PROGRESS_FOR_DAY_ALIAS + DOT + ProgressForDayFields.TECHNOLOGY_OPERATION_COMPONENT, TECHNOLOGY_OPERATION_COMPONENT_ALIAS, JoinType.INNER); scb.add(in(PROGRESS_FOR_DAY_ALIAS + DOT + ID, pfdIds)); if (additionalCriteria != null) { scb.add(additionalCriteria); } scb.addOrder(desc(QUANTITY_SUM_PROJECTION)); Entity projection = scb.setMaxResults(1).uniqueResult(); BigDecimal quantitiesSum = projection.getDecimalField(QUANTITY_SUM_PROJECTION); return ObjectUtils.defaultIfNull(quantitiesSum, BigDecimal.ZERO); }