Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

In this page you can find the example usage for java.math BigDecimal add.

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:mobi.nordpos.catalog.action.ProductCreateActionBean.java

public Resolution add() {
    Product product = getProduct();// ww  w .  j  a  v a 2s . c om
    product.setId(UUID.randomUUID().toString());
    try {
        productPersist.init(getDataBaseConnection());
        taxPersist.init(getDataBaseConnection());
        product.setTax(taxPersist.read(product.getTaxCategory().getId()));
        BigDecimal taxRate = product.getTax().getRate();

        if (getIsTaxInclude() && taxRate != BigDecimal.ZERO) {
            BigDecimal bdTaxRateMultiply = taxRate.add(BigDecimal.ONE);
            product.setPriceSell(product.getPriceSell().divide(bdTaxRateMultiply, MathContext.DECIMAL64));
        }

        getContext().getMessages().add(new SimpleMessage(getLocalizationKey("message.Product.added"),
                productPersist.add(product).getName(), product.getProductCategory().getName()));
    } catch (SQLException ex) {
        getContext().getValidationErrors().addGlobalError(new SimpleError(ex.getMessage()));
        return getContext().getSourcePageResolution();
    }
    return new ForwardResolution(CategoryProductListActionBean.class).addParameter("category.id",
            product.getProductCategory().getId());
}

From source file:de.hybris.platform.accountsummaryaddon.document.populators.B2BAmountBalancePopulator.java

private BigDecimal sumOfOpenAmount(final Collection<B2BDocumentModel> documents) {
    BigDecimal total = BigDecimal.ZERO;
    for (final B2BDocumentModel document : documents) {
        if (document.getDocumentType().getIncludeInOpenBalance().booleanValue()) {
            if (document.getOpenAmount() != null) {
                total = total.add(document.getOpenAmount());
            }/*from w w w.j  a va2  s  .com*/
        }
    }
    return total;
}

From source file:com.ar.dev.tierra.api.controller.NotaCreditoController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public ResponseEntity<?> update(OAuth2Authentication authentication, @RequestBody NotaCredito notaCredito) {
    Usuarios user = facadeService.getUsuariosDAO().findUsuarioByUsername(authentication.getName());
    notaCredito.setUsuarioModificacion(user.getIdUsuario());
    notaCredito.setFechaModificacion(new Date());
    BigDecimal montoUpdate = new BigDecimal(BigInteger.ZERO);
    List<DetalleNotaCredito> list = facadeService.getDetalleNotaCreditoDAO()
            .getByNotaCredito(notaCredito.getIdNotaCredito());
    for (DetalleNotaCredito detalleNotaCredito : list) {
        montoUpdate = montoUpdate.add(detalleNotaCredito.getMonto());
    }//from  w ww . j  av  a 2  s .co m
    notaCredito.setMontoTotal(montoUpdate);
    facadeService.getNotaCreditoDAO().update(notaCredito);
    JsonResponse msg = new JsonResponse("Success", "Nota de credito modificada con exito");
    return new ResponseEntity<>(msg, HttpStatus.OK);
}

From source file:com.siapa.managedbean.DetalleMuestreoManagedBean.java

@Override
public void saveNew(ActionEvent event) {
    DetalleMuestreo detallemuestreo = getDetallemuestreo();
    detallemuestreo.setIdMuestreo(muestreo);
    detallemuestreoService.save(detallemuestreo);
    BigInteger cant = detallemuestreoService.cantidad(muestreo.getIdMuestreo());

    BigDecimal dividir = new BigDecimal(cant);
    List<DetalleMuestreo> q = detallemuestreoService.findAll();
    BigDecimal suma = BigDecimal.ZERO;
    BigDecimal promedio = BigDecimal.ZERO;

    for (DetalleMuestreo detalle : q) {
        if (detalle.getIdMuestreo().getIdMuestreo() == muestreo.getIdMuestreo()) {
            suma = suma.add(detalle.getPesoDetalleMuestreo());
        }/* w w w .  j  a v  a2 s. com*/
    }
    int sumaint = suma.intValue();
    int cantint = cant.intValue();
    //int prom=sumaint/cantint;
    //  promedio=new BigDecimal(prom);
    //  System.out.println(prom);
    promedio = suma.divide(dividir);
    Muestreo newMuestreo = getMuestreo();
    newMuestreo.setPesoPromedioMuestreo(suma.divide(dividir));
    //  muestreo.setPesoPromedioMuestreo(suma);
    System.out.println(promedio);
    muestreoService.merge(newMuestreo);

    loadLazyModels();
    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage(null, new FacesMessage("Successful"));
    try {
        FacesContext context1 = FacesContext.getCurrentInstance();
        context1.getExternalContext().redirect("/siapa/views/detalleMuestreo/index.xhtml");
    } catch (IOException e) {

    }

}

From source file:ustc.sse.controller.DataMiningController.java

/**
 * /*from  w ww.  j a  v a2s .c om*/
 * @param request
 * @param response
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping("autoDocument")
public String autoDocument(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    TrainSampleDataManager.process();
    String article = new String((request.getParameter("article")).getBytes("ISO-8859-1"), "UTF-8");
    //"????????29???????????29??????????";
    //String s="????????????Foursquare?????";
    //String s="???????75%80????";
    //String s=" ????????CEOCEO????";
    //String s="???44621? ?????446?????3113119.1862%????20062007???????????????(?)";
    //String s="?Uber2.58????Uber???";
    //String s="? ??";
    Set<String> words = ChineseTokenizer.segStr(article).keySet();

    Map<String, BigDecimal> resultMap = MultinomialModelNaiveBayes
            .classifyResult(DefaultStopWordsHandler.dropStopWords(words));
    Set<String> set = resultMap.keySet();

    docClass.put("C000007", "");
    docClass.put("C000008", "?");
    docClass.put("C000010", "IT");
    docClass.put("C000013", "?");
    docClass.put("C000014", "");
    docClass.put("C000016", "");
    docClass.put("C000020", "");
    docClass.put("C000022", "?");
    docClass.put("C000023", "");
    docClass.put("C000024", "");

    List<Classifer> classifers = new LinkedList<Classifer>();
    BigDecimal total = new BigDecimal(0);
    BigDecimal probability = new BigDecimal(0);
    for (String str : set) {
        probability = resultMap.get(str);
        total = total.add(probability);
        log.info("classifer:" + str + "     probability:" + probability);
        Classifer classifer = new Classifer(docClass.get(str), probability);
        classifers.add(classifer);
    }
    //
    for (Classifer classifer : classifers) {
        classifer.setProbability((classifer.getProbability()).divide(total, 2, BigDecimal.ROUND_HALF_EVEN));
    }

    request.setAttribute("classifers", classifers);

    String classifyName = docClass.get(MultinomialModelNaiveBayes.getClassifyResultName());
    request.setAttribute("classifyName", classifyName);
    log.info("The final result:" + classifyName);
    return "autoDocument";
}

From source file:id.ac.ipb.ilkom.training.controller.OrderController.java

@RequestMapping(value = "/add-to-cart", method = RequestMethod.POST)
@ResponseBody//from  w  w  w. ja  v a  2s .co  m
public AddToCartResponse addToCart(Integer productId, Integer quantity, HttpSession session) {
    //check if user already login or not
    Customer customer = (Customer) session.getAttribute("customer");
    if (customer == null) {
        AddToCartResponse response = new AddToCartResponse();
        response.setResult(false);
        response.setErrorMessage("Please login before buy product.");
        return response;
    }
    //check product
    Product product = productService.getProduct(productId);
    if (product == null) {
        AddToCartResponse response = new AddToCartResponse();
        response.setResult(false);
        response.setErrorMessage("Product id " + productId + " is not found .");
        return response;
    }
    Order order = (Order) session.getAttribute("cart");
    if (order == null) {
        List<OrderItem> orderItems = new ArrayList<>();
        order = new Order();
        order.setOrderItems(orderItems);
    }
    boolean isProductFoundInOrderItems = false;
    for (OrderItem orderItem : order.getOrderItems()) {
        if (orderItem.getProduct().getId().equals(productId)) {
            orderItem.setQuantity(orderItem.getQuantity() + quantity);
            isProductFoundInOrderItems = true;
            break;
        }
    }
    if (!isProductFoundInOrderItems) {
        OrderItem orderItem = new OrderItem();
        orderItem.setQuantity(quantity);
        orderItem.setProduct(product);
        orderItem.setPrice(product.getPrice());
        orderItem.setOrder(order); //tambahan
        order.getOrderItems().add(orderItem);
    }
    BigDecimal total = BigDecimal.ZERO;
    for (OrderItem orderItem : order.getOrderItems()) {
        BigDecimal price = orderItem.getPrice();
        BigDecimal subTotal = price.multiply(new BigDecimal(orderItem.getQuantity()));
        total = total.add(subTotal);
    }
    order.setCreatedDate(new Date());
    order.setCustomer(customer);
    order.setTotal(total);
    //check
    session.setAttribute("cart", order);
    AddToCartResponse response = new AddToCartResponse();
    response.setResult(true);
    return response;
}

From source file:com.cloudera.sqoop.mapreduce.db.TextSplitter.java

/**
 * Return a BigDecimal representation of string 'str' suitable for use in a
 * numerically-sorting order.//from  w  ww .  j  av a  2 s. c  om
 */
BigDecimal stringToBigDecimal(String str) {
    // Start with 1/65536 to compute the first digit.
    BigDecimal curPlace = ONE_PLACE;
    BigDecimal result = BigDecimal.ZERO;

    int len = Math.min(str.length(), MAX_CHARS);

    for (int i = 0; i < len; i++) {
        int codePoint = str.codePointAt(i);
        result = result.add(tryDivide(new BigDecimal(codePoint), curPlace));
        // advance to the next less significant place. e.g., 1/(65536^2) for the
        // second char.
        curPlace = curPlace.multiply(ONE_PLACE);
    }

    return result;
}

From source file:fsm.series.Series_CF.java

@Override
public double getFunctionValue(double y, int m) {

    double um = getMu_m(m);

    double alphaM = (sin(um) + sinh(um)) / (cos(um) + cosh(um));

    double km = um / a;

    BigDecimal Ym;/*from   w ww.j a  v a2  s .com*/

    BigDecimal cosh = new BigDecimal(-alphaM * -cosh(km * y));
    BigDecimal sinh = new BigDecimal(-sinh(km * y));
    BigDecimal sin = new BigDecimal(sin(km * y));
    BigDecimal cos = new BigDecimal(-alphaM * cos(km * y));

    Ym = (cos.add(sin).add(sinh).add(cosh));

    return Ym.doubleValue();
}

From source file:com.osafe.events.CheckOutEvents.java

public static String autoCaptureAuthPayments(HttpServletRequest request, HttpServletResponse response) {
    // warning there can only be ONE payment preference for this to work
    // you cannot accept multiple payment type when using an external gateway
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    String orderId = (String) request.getAttribute("orderId");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
    String result = "success";

    //LS: Note: This service is automatically called from controller_ecommerce (autoCpaturePayments) checkout flow.
    //If a client wants to only 'approve' orders and not capture when order is placed update parameter CHECKOUT_CC_CAPTURE_FLAG=FALSE.
    String autoCapture = Util.getProductStoreParm(request, "CHECKOUT_CC_CAPTURE_FLAG");
    if (UtilValidate.isNotEmpty(autoCapture) && "FALSE".equals(autoCapture.toUpperCase())) {
        OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        return result;

    }/*from   w w w . ja  v  a 2 s. c om*/

    try {
        /*
         * A bit of a hack here to get the admin user since to capture payments and complete the order requires a user who has
         * the proper security permissions
         */
        GenericValue sysLogin = delegator.findByPrimaryKeyCache("UserLogin",
                UtilMisc.toMap("userLoginId", "admin"));

        List<GenericValue> lOrderPaymentPreference = delegator.findByAnd("OrderPaymentPreference",
                UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_AUTHORIZED"));
        if (UtilValidate.isNotEmpty(lOrderPaymentPreference)) {
            /*
             * This will complete the order generate invoice and capture any payments.
             * OrderChangeHelper.completeOrder(dispatcher, sysLogin, orderId);
             */

            /*
             * To only capture payments and leave the order in approved status. Remove the complete order call,
             */
            //Get the amount to capture
            BigDecimal amountToCapture = BigDecimal.ZERO;
            for (GenericValue orderPaymentPreference : lOrderPaymentPreference) {
                amountToCapture = amountToCapture.add(orderPaymentPreference.getBigDecimal("maxAmount"))
                        .setScale(scale, rounding);
            }

            Map<String, Object> serviceContext = UtilMisc.toMap("userLogin", sysLogin, "orderId", orderId,
                    "captureAmount", amountToCapture);
            String captureResp = "";
            try {
                Map callResult = dispatcher.runSync("captureOrderPayments", serviceContext);
                if (ModelService.RESPOND_ERROR.equals(callResult.get(ModelService.RESPONSE_MESSAGE))) {
                    captureResp = "ERROR";
                } else {
                    captureResp = (String) callResult.get("processResult");
                }
                ServiceUtil.getMessages(request, callResult, null);
            } catch (Exception e) {
                captureResp = "ERROR";
                Debug.logError(e, module);
            }
            if (captureResp.equals("FAILED") || captureResp.equals("ERROR")) {
                OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
                // Remove all payment method from cart except GIFT_CARD
                List pmi = cart.getPaymentMethodIds();
                List giftCards = cart.getGiftCards();
                List giftCardPmi = new LinkedList();
                if (UtilValidate.isNotEmpty(giftCards)) {
                    Iterator i = giftCards.iterator();
                    while (i.hasNext()) {
                        GenericValue gc = (GenericValue) i.next();
                        giftCardPmi.add(gc.getString("paymentMethodId"));
                    }
                    pmi.removeAll(giftCardPmi);
                }
                cart.clearPaymentMethodsById(pmi);
                // Set order id as null in cart because order has been canceled
                cart.setOrderId(null);
                return "error";
            }
        } else {
            //If no payments were authorized, there are no payments to capture; approve the order.
            OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);

        }

    } catch (Exception e) {
        Debug.logError(e, module);
    }

    return result;
}

From source file:com.ar.dev.tierra.api.controller.DetalleFacturaController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public ResponseEntity<?> update(OAuth2Authentication authentication,
        @RequestBody DetalleFactura detalleFactura) {
    Usuarios user = facadeService.getUsuariosDAO().findUsuarioByUsername(authentication.getName());
    Factura factura = facadeService.getFacturaDAO().searchById(detalleFactura.getFactura().getIdFactura());
    detalleFactura.setUsuarioModificacion(user.getIdUsuario());
    detalleFactura.setFechaModificacion(new Date());
    facadeService.getDetalleFacturaDAO().update(detalleFactura);
    /*Traemos lista de detalles, calculamos su nuevo total y actualizamos*/
    List<DetalleFactura> detallesFactura = facadeService.getDetalleFacturaDAO()
            .facturaDetalle(detalleFactura.getFactura().getIdFactura());
    BigDecimal sumMonto = new BigDecimal(BigInteger.ZERO);
    for (DetalleFactura detailList : detallesFactura) {
        sumMonto = sumMonto.add(detailList.getTotalDetalle());
    }//  w ww  . j  a v a  2  s  . co  m
    factura.setTotal(sumMonto);
    factura.setFechaModificacion(new Date());
    factura.setUsuarioModificacion(user.getIdUsuario());
    facadeService.getFacturaDAO().update(factura);
    JsonResponse msg = new JsonResponse("Success", "Detalle modificado con exito");
    return new ResponseEntity<>(msg, HttpStatus.OK);
}