Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

To view the source code for java.math BigDecimal ONE.

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsRateInquire(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");

    // check for 0 weight
    BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight");
    if (shippableWeight.compareTo(BigDecimal.ZERO) == 0) {
        // TODO: should we return an error, or $0.00 ?
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale));
    }//from w  w w  .  j av  a2s  . com

    // get the origination ZIP
    String originationZip = null;
    GenericValue productStore = ProductStoreWorker.getProductStore(((String) context.get("productStoreId")),
            delegator);
    if (productStore != null && productStore.get("inventoryFacilityId") != null) {
        GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator,
                productStore.getString("inventoryFacilityId"),
                UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
        if (facilityContactMech != null) {
            try {
                GenericValue shipFromAddress = EntityQuery.use(delegator).from("PostalAddress")
                        .where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne();
                if (shipFromAddress != null) {
                    originationZip = shipFromAddress.getString("postalCode");
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
        }
    }
    if (UtilValidate.isEmpty(originationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineOriginationZip", locale));
    }

    // get the destination ZIP
    String destinationZip = null;
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    if (UtilValidate.isNotEmpty(shippingContactMechId)) {
        try {
            GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress")
                    .where("contactMechId", shippingContactMechId).queryOne();
            if (shipToAddress != null) {
                if (!domesticCountries.contains(shipToAddress.getString("countryGeoId"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsRateInquiryOnlyInUsDestinations", locale));
                }
                destinationZip = shipToAddress.getString("postalCode");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (UtilValidate.isEmpty(destinationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineDestinationZip", locale));
    }

    // get the service code
    String serviceCode = null;
    try {
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId",
                        (String) context.get("carrierPartyId"), "roleTypeId",
                        (String) context.get("carrierRoleTypeId"))
                .queryOne();
        if (carrierShipmentMethod != null) {
            serviceCode = carrierShipmentMethod.getString("carrierServiceCode").toUpperCase();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (UtilValidate.isEmpty(serviceCode)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineServiceCode", locale));
    }

    // create the request document
    Document requestDocument = createUspsRequestDocument("RateV2Request", true, delegator,
            shipmentGatewayConfigId, resource);

    // TODO: 70 lb max is valid for Express, Priority and Parcel only - handle other methods
    BigDecimal maxWeight = new BigDecimal("70");
    String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight",
            resource, "shipment.usps.max.estimate.weight", "70");
    try {
        maxWeight = new BigDecimal(maxWeightStr);
    } catch (NumberFormatException e) {
        Debug.logWarning(
                "Error parsing max estimate weight string [" + maxWeightStr + "], using default instead",
                module);
        maxWeight = new BigDecimal("70");
    }

    List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo"));
    List<Map<String, BigDecimal>> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight);
    boolean isOnePackage = packages.size() == 1; // use shippableWeight if there's only one package
    // TODO: Up to 25 packages can be included per request - handle more than 25
    for (ListIterator<Map<String, BigDecimal>> li = packages.listIterator(); li.hasNext();) {
        Map<String, BigDecimal> packageMap = li.next();

        BigDecimal packageWeight = isOnePackage ? shippableWeight
                : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO);
        if (packageWeight.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }

        Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                requestDocument);
        packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples)

        UtilXml.addChildElementValue(packageElement, "Service", serviceCode, requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipOrigination",
                StringUtils.substring(originationZip, 0, 5), requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipDestination",
                StringUtils.substring(destinationZip, 0, 5), requestDocument);

        BigDecimal weightPounds = packageWeight.setScale(0, BigDecimal.ROUND_FLOOR);
        // for Parcel post, the weight must be at least 1 lb
        if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPounds.compareTo(BigDecimal.ONE) < 0)) {
            weightPounds = BigDecimal.ONE;
            packageWeight = BigDecimal.ZERO;
        }
        // (packageWeight % 1) * 16 (Rounded up to 0 dp)
        BigDecimal weightOunces = packageWeight.remainder(BigDecimal.ONE).multiply(new BigDecimal("16"))
                .setScale(0, BigDecimal.ROUND_CEILING);

        UtilXml.addChildElementValue(packageElement, "Pounds", weightPounds.toPlainString(), requestDocument);
        UtilXml.addChildElementValue(packageElement, "Ounces", weightOunces.toPlainString(), requestDocument);

        // TODO: handle other container types, package sizes, and machinable packages
        // IMPORTANT: Express or Priority Mail will fail if you supply a Container tag: you will get a message like
        // Invalid container type. Valid container types for Priority Mail are Flat Rate Envelope and Flat Rate Box.
        /* This is an official response from the United States Postal Service:
        The <Container> tag is used to specify the flat rate mailing options, or the type of large or oversized package being mailed.
        If you are wanting to get regular Express Mail rates, leave the <Container> tag empty, or do not include it in the request at all.
         */
        if ("Parcel".equalsIgnoreCase(serviceCode)) {
            UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
        }
        UtilXml.addChildElementValue(packageElement, "Size", "REGULAR", requestDocument);
        UtilXml.addChildElementValue(packageElement, "Machinable", "false", requestDocument);
    }

    // send the request
    Document responseDocument = null;
    try {
        responseDocument = sendUspsRequest("RateV2", requestDocument, delegator, shipmentGatewayConfigId,
                resource, locale);
    } catch (UspsRequestException e) {
        Debug.logInfo(e, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    if (responseDocument == null) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    List<? extends Element> rates = UtilXml.childElementList(responseDocument.getDocumentElement(), "Package");
    if (UtilValidate.isEmpty(rates)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    BigDecimal estimateAmount = BigDecimal.ZERO;
    for (Element packageElement : rates) {
        try {
            Element postageElement = UtilXml.firstChildElement(packageElement, "Postage");
            BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(postageElement, "Rate"));
            estimateAmount = estimateAmount.add(packageAmount);
        } catch (NumberFormatException e) {
            Debug.logInfo(e, module);
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shippingEstimateAmount", estimateAmount);
    return result;
}

From source file:org.openhab.persistence.dynamodb.internal.AbstractDynamoDBItemSerializationTest.java

@Test
public void testOnOffTypeWithDimmerItem() throws IOException {
    DynamoDBItem<?> dbitemOff = testStateGeneric(OnOffType.OFF, BigDecimal.ZERO);
    testAsHistoricGeneric(dbitemOff, new DimmerItem("foo"), new PercentType(BigDecimal.ZERO));

    DynamoDBItem<?> dbitemOn = testStateGeneric(OnOffType.ON, BigDecimal.ONE);
    testAsHistoricGeneric(dbitemOn, new DimmerItem("foo"), new PercentType(BigDecimal.ONE));
}

From source file:org.openvpms.archetype.rules.finance.invoice.ChargeItemDocumentLinkerTestCase.java

/**
 * Helper to create an invoice item.//w w  w  .  ja  va  2s  .  com
 *
 * @param patient   the patient
 * @param product   the product
 * @param author    the author
 * @param clinician the clinician
 * @return a new invoice item
 */
private FinancialAct createItem(Party patient, Product product, User author, User clinician) {
    FinancialAct item = FinancialTestHelper.createChargeItem(CustomerAccountArchetypes.INVOICE_ITEM, patient,
            product, BigDecimal.ONE);
    ActBean bean = new ActBean(item);
    bean.addNodeParticipation("author", author);
    bean.addNodeParticipation("clinician", clinician);
    return item;
}

From source file:com.workday.autoparse.xml.demo.XmlParserTest.java

@Test
public void testMissingAttributesAreNotSet()
        throws ParseException, UnexpectedChildException, UnknownElementException {
    XmlStreamParser parser = XmlStreamParserFactory.newXmlStreamParser();
    InputStream in = getInputStreamOf("missing-attributes.xml");

    DemoModel model = (DemoModel) parser.parseStream(in);

    assertTrue(model.myBoxedBoolean);//from w  w  w.j  a  va2 s.  com
    assertTrue(model.myPrimitiveBoolean);
    assertEquals(BigDecimal.ONE, model.myBigDecimal);
    assertEquals(BigInteger.TEN, model.myBigInteger);
    assertEquals(-1, model.myPrimitiveByte);
    assertEquals(Byte.valueOf((byte) -1), model.myBoxedByte);
    assertEquals('a', model.myPrimitiveChar);
    assertEquals(Character.valueOf('a'), model.myBoxedChar);
    assertEquals(-1.0, model.myPrimitiveDouble, DOUBLE_E);
    assertEquals(Double.valueOf(-1.0), model.myBoxedDouble);
    assertEquals(-1f, model.myPrimitiveFloat, FLOAT_E);
    assertEquals(Float.valueOf(-1f), model.myBoxedFloat);
    assertEquals(-1, model.myPrimitiveInt);
    assertEquals(Integer.valueOf(-1), model.myBoxedInt);
    assertEquals(-1, model.myPrimitiveLong);
    assertEquals(Long.valueOf(-1), model.myBoxedLong);
    assertEquals(-1, model.myPrimitiveShort);
    assertEquals(Short.valueOf((short) -1), model.myBoxedShort);
    assertEquals("default", model.myString);
    assertEquals("default", model.myTextContent);
}

From source file:pe.gob.mef.gescon.hibernate.impl.ConsultaDaoImpl.java

@Override
public List<HashMap> getQueryFilter(HashMap filters) {
    final String fCategoria = (String) filters.get("fCategoria");
    final Date fFromDate = (Date) filters.get("fFromDate");
    final Date fToDate = (Date) filters.get("fToDate");
    final String fType = (String) filters.get("fType");
    final String fCodesBL = (String) filters.get("fCodesBL");
    final String fCodesPR = (String) filters.get("fCodesPR");
    final String fCodesC = (String) filters.get("fCodesC");
    final String fText = (String) filters.get("fText");
    final String order = (String) filters.get("order");
    SimpleDateFormat sdf = new SimpleDateFormat(Constante.FORMAT_DATE_SHORT);
    final StringBuilder sql = new StringBuilder();
    Object object = null;/*from   w w  w .  j ava 2s .  c  o  m*/
    try {
        sql.append("SELECT x.ID, x.NOMBRE, x.SUMILLA, x.IDCATEGORIA, x.CATEGORIA, x.FECHA, ");
        sql.append("       x.IDTIPOCONOCIMIENTO, x.TIPOCONOCIMIENTO, x.IDESTADO, x.ESTADO, x.FLG, ");
        sql.append("       x.SUMA, x.CONTADOR, DECODE(x.CONTADOR,0,0,x.SUMA/x.CONTADOR) AS PROMEDIO ");
        sql.append("FROM (SELECT ");
        sql.append("            a.nbaselegalid AS ID, a.vnumero AS NOMBRE, a.vnombre AS SUMILLA, ");
        sql.append(
                "            a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, ");
        sql.append(
                "            1 AS IDTIPOCONOCIMIENTO, 'Base Legal' AS TIPOCONOCIMIENTO, a.nestadoid AS IDESTADO, c.vnombre AS ESTADO, ");
        sql.append(
                "            0 AS FLG, NVL(SUM(e.ncalificacion),0) AS SUMA, NVL(COUNT(e.ncalificacion),0) AS CONTADOR ");
        sql.append("        FROM TBASELEGAL a ");
        sql.append("        INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
        sql.append("        INNER JOIN MTESTADO_BASELEGAL c ON a.nestadoid = c.nestadoid ");
        sql.append("        LEFT OUTER JOIN TCALIFICACION_BASELEGAL e ON a.nbaselegalid = e.nbaselegalid ");
        sql.append("        WHERE a.nactivo = :ACTIVO ");
        sql.append("        AND c.nestadoid IN (3,4,5,6) AND b.NESTADO = 1 ");
        if (StringUtils.isNotBlank(fCategoria)) {
            sql.append("    AND a.ncategoriaid IN (").append(fCategoria).append(") ");
        }
        if (fFromDate != null) {
            sql.append("    AND TRUNC(a.dfechapublicacion) >= TO_DATE('").append(sdf.format(fFromDate))
                    .append("','dd/mm/yyyy') ");
        }
        if (fToDate != null) {
            sql.append("    AND TRUNC(a.dfechapublicacion) <= TO_DATE('").append(sdf.format(fToDate))
                    .append("','dd/mm/yyyy') ");
        }
        if (StringUtils.isNotBlank(fCodesBL)) {
            sql.append("    AND a.nbaselegalid IN (").append(fCodesBL).append(") ");
        }
        if (StringUtils.isNotBlank(fText)) {
            sql.append("    AND a.vnumero LIKE '%").append(fText).append("%' ");
        }
        sql.append("        GROUP BY a.nbaselegalid, a.vnumero, a.vnombre, a.ncategoriaid, b.vnombre, ");
        sql.append("        a.dfechapublicacion, 1, 'Base Legal', a.nestadoid, c.vnombre, 0 ");
        sql.append("        ) x ");
        sql.append("WHERE 1 IN (").append(fType).append(") "); //BASE LEGAL
        sql.append("UNION ");
        sql.append("SELECT y.ID, y.NOMBRE, y.SUMILLA, y.IDCATEGORIA, y.CATEGORIA, y.FECHA, ");
        sql.append("       y.IDTIPOCONOCIMIENTO, y.TIPOCONOCIMIENTO, y.IDESTADO, y.ESTADO, y.FLG, ");
        sql.append("       y.SUMA, y.CONTADOR, DECODE(y.CONTADOR,0,0,y.SUMA/y.CONTADOR) AS PROMEDIO ");
        sql.append("FROM (SELECT ");
        sql.append(
                "            a.npreguntaid AS ID, a.vasunto AS NOMBRE, a.vdetalle AS SUMILLA, a.ncategoriaid AS IDCATEGORIA, ");
        sql.append(
                "            b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, 2 AS IDTIPOCONOCIMIENTO, ");
        sql.append(
                "            'Preguntas y Respuestas' AS TIPOCONOCIMIENTO, a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO, ");
        sql.append(
                "            0 AS FLG, NVL(SUM(e.ncalificacion),0) AS SUMA, NVL(COUNT(e.ncalificacion),0) AS CONTADOR ");
        sql.append("        FROM TPREGUNTA a ");
        sql.append("        INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
        sql.append("        INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid ");
        sql.append("        LEFT OUTER JOIN TCALIFICACION_PREGUNTA e ON a.npreguntaid = e.npreguntaid ");
        sql.append("        WHERE a.nactivo = :ACTIVO ");
        sql.append("        AND c.nsituacionid = 6 AND b.NESTADO = 1 ");
        if (StringUtils.isNotBlank(fCategoria)) {
            sql.append("    AND a.ncategoriaid IN (").append(fCategoria).append(") ");
        }
        if (fFromDate != null) {
            sql.append("    AND TRUNC(a.dfechacreacion) >= TO_DATE('").append(sdf.format(fFromDate))
                    .append("','dd/mm/yyyy') ");
        }
        if (fToDate != null) {
            sql.append("    AND TRUNC(a.dfechacreacion) <= TO_DATE('").append(sdf.format(fToDate))
                    .append("','dd/mm/yyyy') ");
        }
        if (StringUtils.isNotBlank(fCodesPR)) {
            sql.append("    AND a.npreguntaid IN (").append(fCodesPR).append(") ");
        }
        if (StringUtils.isNotBlank(fText)) {
            sql.append("    AND a.vasunto LIKE '%").append(fText).append("%' ");
        }
        sql.append("        GROUP BY a.npreguntaid, a.vasunto, a.vdetalle, a.ncategoriaid, b.vnombre, ");
        sql.append("        a.dfechapublicacion, 2, 'Preguntas y Respuestas', a.nsituacionid, c.vnombre, 0 ");
        sql.append("        ) y ");
        sql.append("WHERE 2 IN (").append(fType).append(") "); //PREGUNTAS Y RESPUESTAS
        sql.append("UNION ");
        sql.append("SELECT z.ID, z.NOMBRE, z.SUMILLA, z.IDCATEGORIA, z.CATEGORIA, z.FECHA, ");
        sql.append("       z.IDTIPOCONOCIMIENTO, z.TIPOCONOCIMIENTO, z.IDESTADO, z.ESTADO, z.FLG, ");
        sql.append("       z.SUMA, z.CONTADOR, DECODE(z.CONTADOR,0,0,z.SUMA/z.CONTADOR) AS PROMEDIO ");
        sql.append("FROM (SELECT ");
        sql.append("            a.nconocimientoid AS ID, a.vtitulo AS NOMBRE, a.vdescripcion AS SUMILLA, ");
        sql.append(
                "            a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, ");
        sql.append("            a.ntpoconocimientoid AS IDTIPOCONOCIMIENTO, d.vnombre AS TIPOCONOCIMIENTO, ");
        sql.append("            a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO, a.nflgvinculo AS FLG, ");
        sql.append(
                "            NVL(SUM(e.ncalificacion),0) AS SUMA, NVL(COUNT(e.ncalificacion),0) AS CONTADOR ");
        sql.append("        FROM TCONOCIMIENTO a ");
        sql.append("        INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
        sql.append("        INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid ");
        sql.append("        INNER JOIN MTTIPO_CONOCIMIENTO d ON a.ntpoconocimientoid = d.ntpoconocimientoid ");
        sql.append("        AND a.ntpoconocimientoid IN (").append(fType).append(") ");
        sql.append("        LEFT OUTER JOIN TCALIFICACION e ON a.nconocimientoid = e.nconocimientoid ");
        sql.append("        WHERE a.nactivo = :ACTIVO ");
        sql.append("        AND c.nsituacionid = 6 AND b.nestado = 1 ");
        if (StringUtils.isNotBlank(fCategoria)) {
            sql.append("    AND a.ncategoriaid IN (").append(fCategoria).append(") ");
        }
        if (fFromDate != null) {
            sql.append("    AND TRUNC(a.dfechacreacion) >= TO_DATE('").append(sdf.format(fFromDate))
                    .append("','dd/mm/yyyy') ");
        }
        if (fToDate != null) {
            sql.append("    AND TRUNC(a.dfechacreacion) <= TO_DATE('").append(sdf.format(fToDate))
                    .append("','dd/mm/yyyy') ");
        }
        if (StringUtils.isNotBlank(fCodesC)) {
            sql.append("    AND a.nconocimientoid IN (").append(fCodesC).append(") ");
        }
        if (StringUtils.isNotBlank(fText)) {
            sql.append("    AND a.vtitulo LIKE '%").append(fText).append("%' ");
        }
        sql.append(
                "        GROUP BY a.nconocimientoid, a.vtitulo, a.vdescripcion, a.ncategoriaid, b.vnombre, ");
        sql.append(
                "        a.dfechapublicacion, a.ntpoconocimientoid, d.vnombre, a.nsituacionid, c.vnombre, a.nflgvinculo ");
        sql.append("        ) z ");
        sql.append("WHERE (3 IN (").append(fType).append(") OR 4 IN (").append(fType).append(") OR 5 IN (")
                .append(fType).append(") OR 6 IN (").append(fType).append(")) "); //WIKI            
        if (StringUtils.isNotBlank(order)) {
            sql.append("ORDER BY ").append(order);
        } else {
            sql.append("ORDER BY 6 DESC ");
        }

        object = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(sql.toString());
                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                if (StringUtils.isNotBlank(sql.toString())) {
                    query.setParameter("ACTIVO", BigDecimal.ONE);
                }
                return query.list();
            }
        });
    } catch (DataAccessException e) {
        e.getMessage();
        e.printStackTrace();
    }
    return (List<HashMap>) object;
}

From source file:org.openvpms.archetype.rules.supplier.OrderGeneratorTestCase.java

/**
 * Verifies that the package size of existing orders is taken into account when calculating stock to order.
 *///w  ww. jav  a 2  s  .com
@Test
public void testGetOrderableStockForPackageSizeChange() {
    OrderGenerator generator = new OrderGenerator(taxRules, getArchetypeService());
    Party stockLocation = SupplierTestHelper.createStockLocation();
    Party supplier1 = TestHelper.createSupplier();
    Product product1 = TestHelper.createProduct();

    // create an order for 10 boxes, with a package size of 2
    FinancialAct orderItem = createOrderItem(product1, BigDecimal.valueOf(10), 2, BigDecimal.ONE);
    createOrder(orderItem, supplier1, stockLocation, OrderStatus.ACCEPTED, 0, 0, DeliveryStatus.PENDING);

    // set the new package size to 5
    addRelationships(product1, stockLocation, supplier1, true, 0, 200, 10, BigDecimal.valueOf(4), 5);

    List<Stock> stock = generator.getOrderableStock(supplier1, stockLocation, true);
    assertEquals(1, stock.size());

    checkStock(stock, product1, supplier1, stockLocation, 0, 20, 36);
}

From source file:pe.gob.mef.gescon.web.ui.EntidadMB.java

public void save(ActionEvent event) {
    try {// w  ww .  ja  va2s .  co m
        if (CollectionUtils.isEmpty(this.getListaEntidad())) {
            this.setListaEntidad(Collections.EMPTY_LIST);
        }
        Entidad entidad = new Entidad();
        entidad.setVnombre(this.getNombre());
        entidad.setVcodigoentidad(this.getCodigo());
        entidad.setVdescripcion(this.getDescripcion());
        if (!errorValidation(entidad)) {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();
            EntidadService service = (EntidadService) ServiceFinder.findBean("EntidadService");
            entidad.setNentidadid(service.getNextPK());
            entidad.setVnombre(StringUtils.upperCase(this.getNombre().trim()));
            entidad.setVcodigoentidad(this.getCodigo());
            entidad.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim()));
            entidad.setNactivo(BigDecimal.ONE);
            entidad.setDfechacreacion(new Date());
            entidad.setVusuariocreacion(user.getVlogin());
            entidad.setVdepartamento(this.getDepartamento());
            entidad.setVprovincia(this.getProvincia());
            entidad.setVdistrito(this.getDistrito());
            entidad.setVdepartamento(this.getDepartamento());
            entidad.setNtipoid(BigDecimal.valueOf(Long.parseLong(this.getTipoentidad())));
            service.saveOrUpdate(entidad);
            this.setListaEntidad(service.getEntidades());
            this.cleanAttributes();
            RequestContext.getCurrentInstance().execute("PF('newDialog').hide();");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.yes.cart.web.page.component.cart.ShoppingCartItemsList.java

/**
 * Adjust quantity./*  www. j av  a 2 s .c  o  m*/
 *
 * @param productSkuCode sku code
 * @param qtyField       quantity input box
 * @return BookmarkablePageLink for remove one sku from cart command
 */
private Button createAddSeveralSkuButton(final String productSkuCode, final TextField<BigDecimal> qtyField) {
    final Button adjustQuantityButton = new Button(QUANTITY_ADJUST_BUTTON) {
        @Override
        public void onSubmit() {
            String qty = qtyField.getInput();
            if (StringUtils.isNotBlank(qty)) {
                qty = qty.replace(',', '.');
            }
            final String skuCode = productSkuCode;
            /*try {
            skuCode = URLEncoder.encode(productSkuCode, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            skuCode = productSkuCode;
            }*/

            //TODOv2 add flag for product is quantity with float point enabled for this product or not
            //ATM this is CPOINT
            if (NumberUtils.isNumber(qty) /*&& NumberUtils.toInt(qty) >= 1*/) {
                qtyField.setConvertedInput(
                        new BigDecimal(qty).setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP));
                setResponsePage(getPage().getPageClass(),
                        new PageParameters().add(ShoppingCartCommand.CMD_SETQTYSKU, skuCode)
                                .add(ShoppingCartCommand.CMD_SETQTYSKU_P_QTY, qty));

            } else {
                qtyField.setConvertedInput(BigDecimal.ONE.setScale(Constants.DEFAULT_SCALE));
                error(getLocalizer().getString("nonZeroDigits", this, "Need positive integer value"));
            }
        }
    };
    adjustQuantityButton.setDefaultFormProcessing(true);
    return adjustQuantityButton;
}

From source file:org.cirdles.ambapo.LatLongToUTM.java

/**
 * The meridian radius is based on the lines that run north-south on a map
 * UTM easting coordinates are referenced to the center line of the zone 
 * known as the central meridian/*from  ww w.  j  a va2s . c om*/
 * The central meridian is assigned an 
 * easting value of 500,000 meters East.
 * @param meridianRadius
 * @param etaEast
 * @param longitude
 * @param centralMeridian
 * @return BigDecimal easting
 * 
 */
private static BigDecimal calcEasting(BigDecimal meridianRadius, BigDecimal etaEast, BigDecimal longitude,
        BigDecimal centralMeridian) {

    BigDecimal easting = (SCALE_FACTOR.multiply(meridianRadius)).multiply(etaEast);
    BigDecimal eastOfCM = BigDecimal.ONE;

    if (longitude.compareTo(centralMeridian) < 0)
        eastOfCM = eastOfCM.multiply(new BigDecimal(-1));

    easting = FALSE_EASTING.add(eastOfCM.multiply(easting));

    return easting;
}

From source file:pe.gob.mef.gescon.web.ui.PerfilMB.java

public void activar(ActionEvent event) {
    try {// w w  w. jav a  2 s  . c om
        if (event != null) {
            if (this.getSelectedPerfil() != null) {
                LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
                User user = loginMB.getUser();
                PerfilService service = (PerfilService) ServiceFinder.findBean("PerfilService");
                this.getSelectedPerfil().setNactivo(BigDecimal.ONE);
                this.getSelectedPerfil().setDfechamodificacion(new Date());
                this.getSelectedPerfil().setVusuariomodificacion(user.getVlogin());
                service.saveOrUpdate(this.getSelectedPerfil());
                this.setListaPerfils(service.getPerfils());
            } else {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                        "Debe seleccionar el perfil a activar.");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}