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.finra.herd.dao.EmrDaoTest.java

@Test
public void createEmrClusterAssertCallRunEmrJobFlowOptionalParams() throws Exception {
    String clusterName = "clusterName";
    EmrClusterDefinition emrClusterDefinition = new EmrClusterDefinition();
    InstanceDefinitions instanceDefinitions = new InstanceDefinitions();
    instanceDefinitions.setMasterInstances(
            new MasterInstanceDefinition(10, "masterInstanceType", NO_EMR_CLUSTER_DEFINITION_EBS_CONFIGURATION,
                    NO_INSTANCE_SPOT_PRICE, NO_INSTANCE_MAX_SEARCH_PRICE, NO_INSTANCE_ON_DEMAND_THRESHOLD));
    instanceDefinitions.setCoreInstances(
            new InstanceDefinition(20, "coreInstanceType", NO_EMR_CLUSTER_DEFINITION_EBS_CONFIGURATION,
                    BigDecimal.ONE, NO_INSTANCE_MAX_SEARCH_PRICE, NO_INSTANCE_ON_DEMAND_THRESHOLD));
    instanceDefinitions.setTaskInstances(
            new InstanceDefinition(30, "taskInstanceType", NO_EMR_CLUSTER_DEFINITION_EBS_CONFIGURATION,
                    NO_INSTANCE_SPOT_PRICE, NO_INSTANCE_MAX_SEARCH_PRICE, NO_INSTANCE_ON_DEMAND_THRESHOLD));
    emrClusterDefinition.setInstanceDefinitions(instanceDefinitions);
    emrClusterDefinition.setNodeTags(Arrays.asList(new NodeTag("tagName", "tagValue"),
            new NodeTag("", "tagValue"), new NodeTag("tagName", "")));

    emrClusterDefinition.setSshKeyPairName("sshKeyPairName");
    emrClusterDefinition.setSubnetId("subnetId");
    emrClusterDefinition.setKeepAlive(true);
    emrClusterDefinition.setTerminationProtection(true);
    emrClusterDefinition.setHadoopVersion("hadoopVersion");

    emrClusterDefinition.setReleaseLabel("releaseLabel");
    emrClusterDefinition.setApplications(new ArrayList<>());
    {/*from  www  .  j  ava 2s .co  m*/
        EmrClusterDefinitionApplication emrClusterDefinitionApplication = new EmrClusterDefinitionApplication();
        emrClusterDefinitionApplication.setName("applicationName1");
        emrClusterDefinitionApplication.setVersion("applicationVersion1");
        emrClusterDefinitionApplication.setArgs(Arrays.asList("applicationArg1"));
        emrClusterDefinition.getApplications().add(emrClusterDefinitionApplication);
    }
    {
        EmrClusterDefinitionApplication emrClusterDefinitionApplication = new EmrClusterDefinitionApplication();
        emrClusterDefinitionApplication.setName("applicationName2");
        emrClusterDefinitionApplication.setVersion("applicationVersion2");
        emrClusterDefinitionApplication.setArgs(Arrays.asList("applicationArg2"));
        emrClusterDefinitionApplication.setAdditionalInfoList(Arrays
                .asList(new Parameter("applicationAdditionalInfoName2", "applicationAdditionalInfoValue2")));
        emrClusterDefinition.getApplications().add(emrClusterDefinitionApplication);
    }
    emrClusterDefinition.setConfigurations(new ArrayList<>());
    {
        EmrClusterDefinitionConfiguration emrClusterDefinitionConfiguration = new EmrClusterDefinitionConfiguration();
        emrClusterDefinitionConfiguration.setClassification("classification");
        EmrClusterDefinitionConfiguration emrClusterDefinitionConfigurationInner = new EmrClusterDefinitionConfiguration();
        emrClusterDefinitionConfigurationInner.setClassification("classificationInner");
        emrClusterDefinitionConfiguration
                .setConfigurations(Arrays.asList(emrClusterDefinitionConfigurationInner));
        emrClusterDefinitionConfiguration
                .setProperties(Arrays.asList(new Parameter("propertyKey", "propertyValue")));
        emrClusterDefinition.getConfigurations().add(emrClusterDefinitionConfiguration);
    }
    emrClusterDefinition.setLogBucket("logBucket");
    emrClusterDefinition.setVisibleToAll(true);
    emrClusterDefinition.setEc2NodeIamProfileName("ec2NodeIamProfileName");
    emrClusterDefinition.setServiceIamRole("serviceIamRole");
    emrClusterDefinition.setAmiVersion("amiVersion");
    emrClusterDefinition.setAdditionalInfo("additionalInfo");
    emrClusterDefinition.setEncryptionEnabled(true);
    emrClusterDefinition.setDaemonConfigurations(
            Arrays.asList(new Parameter("daemonConfigurationsKey", "daemonConfigurationsValue")));
    ConfigurationFiles configurationFiles = new ConfigurationFiles();
    configurationFiles.getConfigurationFiles()
            .add(new ConfigurationFile("fileNameShortcut", "configFileLocation"));
    KeyValuePairConfigurations keyValuePairConfigurations = new KeyValuePairConfigurations();
    keyValuePairConfigurations.getKeyValuePairConfigurations()
            .add(new KeyValuePairConfiguration("keyValueShortcut", "attribKey", "attribVal"));
    emrClusterDefinition.setHadoopConfigurations(Arrays.asList(configurationFiles, keyValuePairConfigurations));
    emrClusterDefinition.setCustomBootstrapActionAll(new ArrayList<>());
    {
        ScriptDefinition scriptDefinitionAll = new ScriptDefinition();
        scriptDefinitionAll.setScriptName("scriptDefinitionAllName1");
        scriptDefinitionAll.setScriptLocation("scriptDefinitionAllLocation1");
        scriptDefinitionAll.setScriptArguments(Arrays.asList("scriptDefinitionAllArg1"));
        emrClusterDefinition.getCustomBootstrapActionAll().add(scriptDefinitionAll);
    }
    {
        ScriptDefinition scriptDefinitionAll = new ScriptDefinition();
        scriptDefinitionAll.setScriptName("scriptDefinitionAllName2");
        scriptDefinitionAll.setScriptLocation("scriptDefinitionAllLocation2");
        emrClusterDefinition.getCustomBootstrapActionAll().add(scriptDefinitionAll);
    }
    emrClusterDefinition.setCustomBootstrapActionMaster(new ArrayList<>());
    {
        ScriptDefinition scriptDefinitionMaster = new ScriptDefinition();
        scriptDefinitionMaster.setScriptName("scriptDefinitionMasterName1");
        scriptDefinitionMaster.setScriptLocation("scriptDefinitionMasterLocation1");
        scriptDefinitionMaster.setScriptArguments(Arrays.asList("scriptDefinitionMasterArg1"));
        emrClusterDefinition.getCustomBootstrapActionMaster().add(scriptDefinitionMaster);
    }
    {
        ScriptDefinition scriptDefinitionMaster = new ScriptDefinition();
        scriptDefinitionMaster.setScriptName("scriptDefinitionMasterName2");
        scriptDefinitionMaster.setScriptLocation("scriptDefinitionMasterLocation2");
        emrClusterDefinition.getCustomBootstrapActionMaster().add(scriptDefinitionMaster);
    }
    emrClusterDefinition.setHiveVersion("hiveVersion");
    emrClusterDefinition.setPigVersion("pigVersion");
    emrClusterDefinition.setInstallOozie(true);
    emrClusterDefinition.setHadoopJarSteps(
            Arrays.asList(new HadoopJarStep("stepName", "jarLocation", "mainClass", null, true)));
    emrClusterDefinition.setSupportedProduct("supportedProduct");
    emrClusterDefinition.setSecurityConfiguration("securityConfiguration");
    emrClusterDefinition.setScaleDownBehavior("scaleDownBehavior");

    emrClusterDefinition.setMasterSecurityGroup(EMR_MASTER_SECURITY_GROUP);
    emrClusterDefinition.setSlaveSecurityGroup(EMR_SLAVE_SECURITY_GROUP);
    emrClusterDefinition
            .setKerberosAttributes(new EmrClusterDefinitionKerberosAttributes(AD_DOMAIN_JOIN_PASSWORD,
                    AD_DOMAIN_JOIN_USER, CROSS_REALM_TRUST_PRINCIPAL_PASSWORD, KDC_ADMIN_PASSWORD, REALM));
    String clusterId = "clusterId";

    when(mockEmrOperations.runEmrJobFlow(any(), any())).then(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            /*
             * Assert that the given EMR cluster definition produced the correct RunJobFlowRequest
             */
            RunJobFlowRequest runJobFlowRequest = invocation.getArgument(1);
            assertEquals(3, runJobFlowRequest.getInstances().getInstanceGroups().size());
            {
                InstanceGroupConfig instanceGroupConfig = runJobFlowRequest.getInstances().getInstanceGroups()
                        .get(1);
                assertEquals("1", instanceGroupConfig.getBidPrice());
            }
            {
                InstanceGroupConfig instanceGroupConfig = runJobFlowRequest.getInstances().getInstanceGroups()
                        .get(2);
                assertEquals("taskInstanceType", instanceGroupConfig.getInstanceType());
                assertEquals(30, instanceGroupConfig.getInstanceCount().intValue());
            }
            assertEquals("sshKeyPairName", runJobFlowRequest.getInstances().getEc2KeyName());
            assertEquals("subnetId", runJobFlowRequest.getInstances().getEc2SubnetId());
            assertEquals(true, runJobFlowRequest.getInstances().getKeepJobFlowAliveWhenNoSteps());
            assertEquals(true, runJobFlowRequest.getInstances().getTerminationProtected());
            assertEquals("hadoopVersion", runJobFlowRequest.getInstances().getHadoopVersion());
            assertEquals("releaseLabel", runJobFlowRequest.getReleaseLabel());
            assertEquals(2, runJobFlowRequest.getApplications().size());
            {
                Application application = runJobFlowRequest.getApplications().get(0);
                assertEquals("applicationName1", application.getName());
                assertEquals("applicationVersion1", application.getVersion());
                assertEquals(Arrays.asList("applicationArg1"), application.getArgs());
            }
            {
                Application application = runJobFlowRequest.getApplications().get(1);
                Map<String, String> additionalInfo = application.getAdditionalInfo();
                assertEquals(1, additionalInfo.size());
                assertEquals("applicationAdditionalInfoValue2",
                        additionalInfo.get("applicationAdditionalInfoName2"));
            }
            assertEquals(1, runJobFlowRequest.getConfigurations().size());
            {
                Configuration configuration = runJobFlowRequest.getConfigurations().get(0);
                assertEquals("classification", configuration.getClassification());
                assertEquals(1, configuration.getConfigurations().size());
                {
                    Configuration configurationInner = configuration.getConfigurations().get(0);
                    assertEquals("classificationInner", configurationInner.getClassification());
                }
                assertEquals(1, configuration.getProperties().size());
                assertEquals("propertyValue", configuration.getProperties().get("propertyKey"));
            }
            assertEquals("logBucket", runJobFlowRequest.getLogUri());
            assertEquals(true, runJobFlowRequest.getVisibleToAllUsers());
            assertEquals("ec2NodeIamProfileName", runJobFlowRequest.getJobFlowRole());
            assertEquals("serviceIamRole", runJobFlowRequest.getServiceRole());
            assertEquals("amiVersion", runJobFlowRequest.getAmiVersion());
            assertEquals("additionalInfo", runJobFlowRequest.getAdditionalInfo());
            assertEquals(7, runJobFlowRequest.getBootstrapActions().size());
            {
                BootstrapActionConfig bootstrapActionConfig = runJobFlowRequest.getBootstrapActions().get(0);
                assertEquals("emr.encryption.script", bootstrapActionConfig.getName());
                ScriptBootstrapActionConfig scriptBootstrapAction = bootstrapActionConfig
                        .getScriptBootstrapAction();
                assertEquals("s3:////herd_SCRIPTS/encrypt_disks.sh", scriptBootstrapAction.getPath());
                assertEquals(0, scriptBootstrapAction.getArgs().size());
            }
            {
                BootstrapActionConfig bootstrapActionConfig = runJobFlowRequest.getBootstrapActions().get(1);
                assertEquals("emr.aws.configure.daemon", bootstrapActionConfig.getName());
                ScriptBootstrapActionConfig scriptBootstrapAction = bootstrapActionConfig
                        .getScriptBootstrapAction();
                assertEquals("s3://elasticmapreduce/bootstrap-actions/configure-daemons",
                        scriptBootstrapAction.getPath());
                assertEquals(Arrays.asList("daemonConfigurationsKey=daemonConfigurationsValue"),
                        scriptBootstrapAction.getArgs());
            }
            {
                BootstrapActionConfig bootstrapActionConfig = runJobFlowRequest.getBootstrapActions().get(2);
                assertEquals("emr.aws.configure.hadoop", bootstrapActionConfig.getName());
                ScriptBootstrapActionConfig scriptBootstrapAction = bootstrapActionConfig
                        .getScriptBootstrapAction();
                assertEquals("s3://us-east-1.elasticmapreduce/bootstrap-actions/configure-hadoop",
                        scriptBootstrapAction.getPath());
                assertEquals(Arrays.asList("fileNameShortcut", "configFileLocation", "keyValueShortcut",
                        "attribKey=attribVal"), scriptBootstrapAction.getArgs());
            }
            {
                BootstrapActionConfig bootstrapActionConfig = runJobFlowRequest.getBootstrapActions().get(3);
                assertEquals("scriptDefinitionAllName1", bootstrapActionConfig.getName());
                ScriptBootstrapActionConfig scriptBootstrapAction = bootstrapActionConfig
                        .getScriptBootstrapAction();
                assertEquals("scriptDefinitionAllLocation1", scriptBootstrapAction.getPath());
                assertEquals(Arrays.asList("scriptDefinitionAllArg1"), scriptBootstrapAction.getArgs());
            }
            {
                BootstrapActionConfig bootstrapActionConfig = runJobFlowRequest.getBootstrapActions().get(4);
                ScriptBootstrapActionConfig scriptBootstrapAction = bootstrapActionConfig
                        .getScriptBootstrapAction();
                assertEquals(0, scriptBootstrapAction.getArgs().size());
            }
            {
                BootstrapActionConfig bootstrapActionConfig = runJobFlowRequest.getBootstrapActions().get(5);
                assertEquals("scriptDefinitionMasterName1", bootstrapActionConfig.getName());
                ScriptBootstrapActionConfig scriptBootstrapAction = bootstrapActionConfig
                        .getScriptBootstrapAction();
                assertEquals("s3://elasticmapreduce/bootstrap-actions/run-if", scriptBootstrapAction.getPath());
                assertEquals(Arrays.asList("instance.isMaster=true", "scriptDefinitionMasterLocation1",
                        "scriptDefinitionMasterArg1"), scriptBootstrapAction.getArgs());
            }
            {
                BootstrapActionConfig bootstrapActionConfig = runJobFlowRequest.getBootstrapActions().get(6);
                ScriptBootstrapActionConfig scriptBootstrapAction = bootstrapActionConfig
                        .getScriptBootstrapAction();
                assertEquals(Arrays.asList("instance.isMaster=true", "scriptDefinitionMasterLocation2"),
                        scriptBootstrapAction.getArgs());
            }
            assertEquals(Arrays.asList("supportedProduct"), runJobFlowRequest.getSupportedProducts());
            assertEquals("securityConfiguration", runJobFlowRequest.getSecurityConfiguration());
            assertEquals("scaleDownBehavior", runJobFlowRequest.getScaleDownBehavior());
            assertEquals(EMR_MASTER_SECURITY_GROUP,
                    runJobFlowRequest.getInstances().getEmrManagedMasterSecurityGroup());
            assertEquals(EMR_SLAVE_SECURITY_GROUP,
                    runJobFlowRequest.getInstances().getEmrManagedSlaveSecurityGroup());
            assertEquals(
                    new KerberosAttributes().withADDomainJoinPassword(AD_DOMAIN_JOIN_PASSWORD)
                            .withADDomainJoinUser(AD_DOMAIN_JOIN_USER)
                            .withCrossRealmTrustPrincipalPassword(CROSS_REALM_TRUST_PRINCIPAL_PASSWORD)
                            .withKdcAdminPassword(KDC_ADMIN_PASSWORD).withRealm(REALM),
                    runJobFlowRequest.getKerberosAttributes());
            return clusterId;
        }
    });

    assertEquals(clusterId, emrDao.createEmrCluster(clusterName, emrClusterDefinition, getAwsParamsDto()));
}

From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java

private void setAutoEntrainment(double value) {
    double val = new BigDecimal(value * 100).divide(BigDecimal.ONE, 0, RoundingMode.HALF_UP).doubleValue();
    if (entrainmentFrequency.getValue() == val)
        return;/*from ww  w. j  a va2  s . c  o m*/
    isEntrainerEntrainmentFrequencyMessage = true;
    entrainmentFrequency.setValue((int) val);
}

From source file:adalid.commons.util.ObjUtils.java

public static BigDecimal reciprocal(Object o) {
    BigDecimal pdq = NumUtils.numberToBigDecimal(o);
    return pdq == null || pdq.equals(BigDecimal.ZERO) ? null : BigDecimal.ONE.divide(pdq);
}

From source file:org.ofbiz.order.shoppingcart.ShoppingCartEvents.java

/** Event to add an item to the shopping cart. */
public static String addToCart(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ShoppingCart cart = getCartObject(request);
    ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
    String controlDirective = null;
    Map<String, Object> result = null;
    String productId = null;//  ww  w .jav a2 s  .  c o  m
    String parentProductId = null;
    String itemType = null;
    String itemDescription = null;
    String productCategoryId = null;
    String priceStr = null;
    BigDecimal price = null;
    String quantityStr = null;
    BigDecimal quantity = BigDecimal.ZERO;
    String reservStartStr = null;
    String reservEndStr = null;
    Timestamp reservStart = null;
    Timestamp reservEnd = null;
    String reservLengthStr = null;
    BigDecimal reservLength = null;
    String reservPersonsStr = null;
    BigDecimal reservPersons = null;
    String accommodationMapId = null;
    String accommodationSpotId = null;
    String shipBeforeDateStr = null;
    String shipAfterDateStr = null;
    Timestamp shipBeforeDate = null;
    Timestamp shipAfterDate = null;
    String numberOfDay = null;

    // not used right now: Map attributes = null;
    String catalogId = CatalogWorker.getCurrentCatalogId(request);
    Locale locale = UtilHttp.getLocale(request);

    //CODIGOLINUX
    TimeZone timeZone = UtilHttp.getTimeZone(request);

    // Get the parameters as a MAP, remove the productId and quantity params.
    Map<String, Object> paramMap = UtilHttp.getCombinedMap(request);

    String itemGroupNumber = (String) paramMap.get("itemGroupNumber");

    // Get shoppingList info if passed
    String shoppingListId = (String) paramMap.get("shoppingListId");
    String shoppingListItemSeqId = (String) paramMap.get("shoppingListItemSeqId");
    if (paramMap.containsKey("ADD_PRODUCT_ID")) {
        productId = (String) paramMap.remove("ADD_PRODUCT_ID");
    } else if (paramMap.containsKey("add_product_id")) {
        Object object = paramMap.remove("add_product_id");
        try {
            productId = (String) object;
        } catch (ClassCastException e) {
            List<String> productList = UtilGenerics.checkList(object);
            productId = productList.get(0);
        }
    }
    if (paramMap.containsKey("PRODUCT_ID")) {
        parentProductId = (String) paramMap.remove("PRODUCT_ID");
    } else if (paramMap.containsKey("product_id")) {
        parentProductId = (String) paramMap.remove("product_id");
    }

    Debug.logInfo("adding item product " + productId, module);
    Debug.logInfo("adding item parent product " + parentProductId, module);

    if (paramMap.containsKey("ADD_CATEGORY_ID")) {
        productCategoryId = (String) paramMap.remove("ADD_CATEGORY_ID");
    } else if (paramMap.containsKey("add_category_id")) {
        productCategoryId = (String) paramMap.remove("add_category_id");
    }
    if (productCategoryId != null && productCategoryId.length() == 0) {
        productCategoryId = null;
    }

    if (paramMap.containsKey("ADD_ITEM_TYPE")) {
        itemType = (String) paramMap.remove("ADD_ITEM_TYPE");
    } else if (paramMap.containsKey("add_item_type")) {
        itemType = (String) paramMap.remove("add_item_type");
    }

    if (UtilValidate.isEmpty(productId)) {
        // before returning error; check make sure we aren't adding a special item type
        if (UtilValidate.isEmpty(itemType)) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "cart.addToCart.noProductInfoPassed", locale));
            return "success"; // not critical return to same page
        }
    } else {
        try {
            String pId = ProductWorker.findProductId(delegator, productId);
            if (pId != null) {
                productId = pId;
            }
        } catch (Throwable e) {
            Debug.logWarning(e, module);
        }
    }

    // check for an itemDescription
    if (paramMap.containsKey("ADD_ITEM_DESCRIPTION")) {
        itemDescription = (String) paramMap.remove("ADD_ITEM_DESCRIPTION");
    } else if (paramMap.containsKey("add_item_description")) {
        itemDescription = (String) paramMap.remove("add_item_description");
    }
    if (itemDescription != null && itemDescription.length() == 0) {
        itemDescription = null;
    }

    // Get the ProductConfigWrapper (it's not null only for configurable items)
    ProductConfigWrapper configWrapper = null;
    configWrapper = ProductConfigWorker.getProductConfigWrapper(productId, cart.getCurrency(), request);

    if (configWrapper != null) {
        if (paramMap.containsKey("configId")) {
            try {
                configWrapper.loadConfig(delegator, (String) paramMap.remove("configId"));
            } catch (Exception e) {
                Debug.logWarning(e, "Could not load configuration", module);
            }
        } else {
            // The choices selected by the user are taken from request and set in the wrapper
            ProductConfigWorker.fillProductConfigWrapper(configWrapper, request);
        }
        if (!configWrapper.isCompleted()) {
            // The configuration is not valid
            request.setAttribute("product_id", productId);
            request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error,
                    "cart.addToCart.configureProductBeforeAddingToCart", locale));
            return "product";
        } else {
            // load the Config Id
            ProductConfigWorker.storeProductConfigWrapper(configWrapper, delegator);
        }
    }

    //Check for virtual products
    if (ProductWorker.isVirtual(delegator, productId)) {

        if ("VV_FEATURETREE".equals(ProductWorker.getProductVirtualVariantMethod(delegator, productId))) {
            // get the selected features.
            List<String> selectedFeatures = new LinkedList<String>();
            Enumeration<String> paramNames = UtilGenerics.cast(request.getParameterNames());
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                if (paramName.startsWith("FT")) {
                    selectedFeatures.add(request.getParameterValues(paramName)[0]);
                }
            }

            // check if features are selected
            if (UtilValidate.isEmpty(selectedFeatures)) {
                request.setAttribute("paramMap", paramMap);
                request.setAttribute("product_id", productId);
                request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
                return "product";
            }

            String variantProductId = ProductWorker.getVariantFromFeatureTree(productId, selectedFeatures,
                    delegator);
            if (UtilValidate.isNotEmpty(variantProductId)) {
                productId = variantProductId;
            } else {
                request.setAttribute("paramMap", paramMap);
                request.setAttribute("product_id", productId);
                request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "cart.addToCart.incompatibilityVariantFeature", locale));
                return "product";
            }

        } else {
            request.setAttribute("paramMap", paramMap);
            request.setAttribute("product_id", productId);
            request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error,
                    "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
            return "product";
        }
    }

    // get the override price
    if (paramMap.containsKey("PRICE")) {
        priceStr = (String) paramMap.remove("PRICE");
    } else if (paramMap.containsKey("price")) {
        priceStr = (String) paramMap.remove("price");
    }
    if (priceStr == null) {
        priceStr = "0"; // default price is 0
    }

    if ("ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
        if (paramMap.containsKey("numberOfDay")) {
            numberOfDay = (String) paramMap.remove("numberOfDay");
            reservStart = UtilDateTime.addDaysToTimestamp(UtilDateTime.nowTimestamp(), 1);
            reservEnd = UtilDateTime.addDaysToTimestamp(reservStart, Integer.valueOf(numberOfDay));
        }
    }

    // get the renting data
    if ("ASSET_USAGE".equals(ProductWorker.getProductTypeId(delegator, productId))
            || "ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
        if (paramMap.containsKey("reservStart")) {
            reservStartStr = (String) paramMap.remove("reservStart");
            if (reservStartStr.length() == 10) // only date provided, no time string?
                reservStartStr += " 00:00:00.000000000"; // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
            if (reservStartStr.length() > 0) {
                try {
                    reservStart = java.sql.Timestamp.valueOf(reservStartStr);
                } catch (Exception e) {
                    Debug.logWarning(e, "Problems parsing Reservation start string: " + reservStartStr, module);
                    reservStart = null;
                    request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                            "cart.addToCart.rental.startDate", locale));
                    return "error";
                }
            } else
                reservStart = null;
        }

        if (paramMap.containsKey("reservEnd")) {
            reservEndStr = (String) paramMap.remove("reservEnd");
            if (reservEndStr.length() == 10) // only date provided, no time string?
                reservEndStr += " 00:00:00.000000000"; // should have format: yyyy-mm-dd hh:mm:ss.fffffffff
            if (reservEndStr.length() > 0) {
                try {
                    reservEnd = java.sql.Timestamp.valueOf(reservEndStr);
                } catch (Exception e) {
                    Debug.logWarning(e, "Problems parsing Reservation end string: " + reservEndStr, module);
                    reservEnd = null;
                    request.setAttribute("_ERROR_MESSAGE_",
                            UtilProperties.getMessage(resource_error, "cart.addToCart.rental.endDate", locale));
                    return "error";
                }
            } else
                reservEnd = null;
        }

        if (reservStart != null && reservEnd != null) {
            reservLength = new BigDecimal(UtilDateTime.getInterval(reservStart, reservEnd))
                    .divide(new BigDecimal("86400000"), generalRounding);
        }

        if (reservStart != null && paramMap.containsKey("reservLength")) {
            reservLengthStr = (String) paramMap.remove("reservLength");
            // parse the reservation Length
            try {
                reservLength = (BigDecimal) ObjectType.simpleTypeConvert(reservLengthStr, "BigDecimal", null,
                        locale);
            } catch (Exception e) {
                Debug.logWarning(e, "Problems parsing reservation length string: " + reservLengthStr, module);
                reservLength = BigDecimal.ONE;
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderReservationLengthShouldBeAPositiveNumber", locale));
                return "error";
            }
        }

        if (reservStart != null && paramMap.containsKey("reservPersons")) {
            reservPersonsStr = (String) paramMap.remove("reservPersons");
            // parse the number of persons
            try {
                reservPersons = (BigDecimal) ObjectType.simpleTypeConvert(reservPersonsStr, "BigDecimal", null,
                        locale);
            } catch (Exception e) {
                Debug.logWarning(e,
                        "Problems parsing reservation number of persons string: " + reservPersonsStr, module);
                reservPersons = BigDecimal.ONE;
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderNumberOfPersonsShouldBeOneOrLarger", locale));
                return "error";
            }
        }

        //check for valid rental parameters
        if (UtilValidate.isEmpty(reservStart) && UtilValidate.isEmpty(reservLength)
                && UtilValidate.isEmpty(reservPersons)) {
            request.setAttribute("product_id", productId);
            request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error,
                    "cart.addToCart.enterBookingInforamtionBeforeAddingToCart", locale));
            return "product";
        }

        //check accommodation for reservations
        if ((paramMap.containsKey("accommodationMapId")) && (paramMap.containsKey("accommodationSpotId"))) {
            accommodationMapId = (String) paramMap.remove("accommodationMapId");
            accommodationSpotId = (String) paramMap.remove("accommodationSpotId");
        }
    }

    // get the quantity
    if (paramMap.containsKey("QUANTITY")) {
        quantityStr = (String) paramMap.remove("QUANTITY");
    } else if (paramMap.containsKey("quantity")) {
        quantityStr = (String) paramMap.remove("quantity");
    }
    if (UtilValidate.isEmpty(quantityStr)) {
        quantityStr = "1"; // default quantity is 1
    }

    // parse the price
    try {
        price = (BigDecimal) ObjectType.simpleTypeConvert(priceStr, "BigDecimal", null, locale);
    } catch (Exception e) {
        Debug.logWarning(e, "Problems parsing price string: " + priceStr, module);
        price = null;
    }

    // parse the quantity
    try {
        quantity = (BigDecimal) ObjectType.simpleTypeConvert(quantityStr, "BigDecimal", null, locale);
        //For quantity we should test if we allow to add decimal quantity for this product an productStore : if not then round to 0
        if (!ProductWorker.isDecimalQuantityOrderAllowed(delegator, productId, cart.getProductStoreId())) {
            quantity = quantity.setScale(0, UtilNumber.getBigDecimalRoundingMode("order.rounding"));
        } else {
            quantity = quantity.setScale(UtilNumber.getBigDecimalScale("order.decimals"),
                    UtilNumber.getBigDecimalRoundingMode("order.rounding"));
        }
    } catch (Exception e) {
        Debug.logWarning(e, "Problems parsing quantity string: " + quantityStr, module);
        quantity = BigDecimal.ONE;
    }

    // get the selected amount
    String selectedAmountStr = null;
    if (paramMap.containsKey("ADD_AMOUNT")) {
        selectedAmountStr = (String) paramMap.remove("ADD_AMOUNT");
    } else if (paramMap.containsKey("add_amount")) {
        selectedAmountStr = (String) paramMap.remove("add_amount");
    }

    // parse the amount
    BigDecimal amount = null;
    if (UtilValidate.isNotEmpty(selectedAmountStr)) {
        try {
            amount = (BigDecimal) ObjectType.simpleTypeConvert(selectedAmountStr, "BigDecimal", null, locale);
        } catch (Exception e) {
            Debug.logWarning(e, "Problem parsing amount string: " + selectedAmountStr, module);
            amount = null;
        }
    } else {
        amount = BigDecimal.ZERO;
    }

    // check for required amount
    if ((ProductWorker.isAmountRequired(delegator, productId))
            && (amount == null || amount.doubleValue() == 0.0)) {
        request.setAttribute("product_id", productId);
        request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error,
                "cart.addToCart.enterAmountBeforeAddingToCart", locale));
        return "product";
    }

    // get the ship before date (handles both yyyy-mm-dd input and full timestamp)
    shipBeforeDateStr = (String) paramMap.remove("shipBeforeDate");
    if (UtilValidate.isNotEmpty(shipBeforeDateStr)) {
        if (shipBeforeDateStr.length() == 10)
            shipBeforeDateStr += " 00:00:00.000";
        try {
            shipBeforeDate = java.sql.Timestamp.valueOf(shipBeforeDateStr);
        } catch (IllegalArgumentException e) {
            Debug.logWarning(e, "Bad shipBeforeDate input: " + e.getMessage(), module);
            shipBeforeDate = null;
        }
    }

    // get the ship after date (handles both yyyy-mm-dd input and full timestamp)
    shipAfterDateStr = (String) paramMap.remove("shipAfterDate");
    if (UtilValidate.isNotEmpty(shipAfterDateStr)) {
        if (shipAfterDateStr.length() == 10)
            shipAfterDateStr += " 00:00:00.000";
        try {
            shipAfterDate = java.sql.Timestamp.valueOf(shipAfterDateStr);
        } catch (IllegalArgumentException e) {
            Debug.logWarning(e, "Bad shipAfterDate input: " + e.getMessage(), module);
            shipAfterDate = null;
        }
    }

    // check for an add-to cart survey
    List<String> surveyResponses = null;
    if (productId != null) {
        String productStoreId = ProductStoreWorker.getProductStoreId(request);
        List<GenericValue> productSurvey = ProductStoreWorker.getProductSurveys(delegator, productStoreId,
                productId, "CART_ADD", parentProductId);
        if (UtilValidate.isNotEmpty(productSurvey)) {
            // TODO: implement multiple survey per product
            GenericValue survey = EntityUtil.getFirst(productSurvey);
            String surveyResponseId = (String) request.getAttribute("surveyResponseId");
            if (surveyResponseId != null) {
                surveyResponses = UtilMisc.toList(surveyResponseId);
            } else {
                String origParamMapId = UtilHttp.stashParameterMap(request);
                Map<String, Object> surveyContext = UtilMisc.<String, Object>toMap("_ORIG_PARAM_MAP_ID_",
                        origParamMapId);
                GenericValue userLogin = cart.getUserLogin();
                String partyId = null;
                if (userLogin != null) {
                    partyId = userLogin.getString("partyId");
                }
                String formAction = "/additemsurvey";
                String nextPage = RequestHandler.getOverrideViewUri(request.getPathInfo());
                if (nextPage != null) {
                    formAction = formAction + "/" + nextPage;
                }
                ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(survey, partyId,
                        surveyContext);
                request.setAttribute("surveyWrapper", wrapper);
                request.setAttribute("surveyAction", formAction); // will be used as the form action of the survey
                return "survey";
            }
        }
    }
    if (surveyResponses != null) {
        paramMap.put("surveyResponses", surveyResponses);
    }

    GenericValue productStore = ProductStoreWorker.getProductStore(request);
    if (productStore != null) {
        String addToCartRemoveIncompat = productStore.getString("addToCartRemoveIncompat");
        String addToCartReplaceUpsell = productStore.getString("addToCartReplaceUpsell");
        try {
            if ("Y".equals(addToCartRemoveIncompat)) {
                List<GenericValue> productAssocs = null;
                EntityCondition cond = EntityCondition
                        .makeCondition(
                                UtilMisc.toList(
                                        EntityCondition.makeCondition(
                                                EntityCondition.makeCondition(
                                                        "productId", EntityOperator.EQUALS, productId),
                                                EntityOperator.OR,
                                                EntityCondition.makeCondition("productIdTo",
                                                        EntityOperator.EQUALS, productId)),
                                        EntityCondition.makeCondition("productAssocTypeId",
                                                EntityOperator.EQUALS, "PRODUCT_INCOMPATABLE")),
                                EntityOperator.AND);
                productAssocs = delegator.findList("ProductAssoc", cond, null, null, null, false);
                productAssocs = EntityUtil.filterByDate(productAssocs);
                List<String> productList = FastList.newInstance();
                for (GenericValue productAssoc : productAssocs) {
                    if (productId.equals(productAssoc.getString("productId"))) {
                        productList.add(productAssoc.getString("productIdTo"));
                        continue;
                    }
                    if (productId.equals(productAssoc.getString("productIdTo"))) {
                        productList.add(productAssoc.getString("productId"));
                        continue;
                    }
                }
                for (ShoppingCartItem sci : cart) {
                    if (productList.contains(sci.getProductId())) {
                        try {
                            cart.removeCartItem(sci, dispatcher);
                        } catch (CartItemModifyException e) {
                            Debug.logError(e.getMessage(), module);
                        }
                    }
                }
            }
            if ("Y".equals(addToCartReplaceUpsell)) {
                List<GenericValue> productList = null;
                EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(
                        EntityCondition.makeCondition("productIdTo", EntityOperator.EQUALS, productId),
                        EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS,
                                "PRODUCT_UPGRADE")),
                        EntityOperator.AND);
                productList = delegator.findList("ProductAssoc", cond, UtilMisc.toSet("productId"), null, null,
                        false);
                if (productList != null) {
                    for (ShoppingCartItem sci : cart) {
                        if (productList.contains(sci.getProductId())) {
                            try {
                                cart.removeCartItem(sci, dispatcher);
                            } catch (CartItemModifyException e) {
                                Debug.logError(e.getMessage(), module);
                            }
                        }
                    }
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e.getMessage(), module);
        }
    }

    // check for alternative packing
    if (ProductWorker.isAlternativePacking(delegator, productId, parentProductId)) {
        GenericValue parentProduct = null;
        try {
            parentProduct = delegator.findOne("Product", UtilMisc.toMap("productId", parentProductId), false);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error getting parent product", module);
        }
        BigDecimal piecesIncluded = BigDecimal.ZERO;
        if (parentProduct != null) {
            piecesIncluded = new BigDecimal(parentProduct.getLong("piecesIncluded"));
            quantity = quantity.multiply(piecesIncluded);
        }
    }

    // Translate the parameters and add to the cart
    result = cartHelper.addToCart(catalogId, shoppingListId, shoppingListItemSeqId, productId,
            productCategoryId, itemType, itemDescription, price, amount, quantity, reservStart, reservLength,
            reservPersons, accommodationMapId, accommodationSpotId, shipBeforeDate, shipAfterDate,
            configWrapper, itemGroupNumber, paramMap, parentProductId);
    controlDirective = processResult(result, request);

    Integer itemId = (Integer) result.get("itemId");
    if (UtilValidate.isNotEmpty(itemId)) {
        request.setAttribute("itemId", itemId);
    }

    // Determine where to send the browser
    if (controlDirective.equals(ERROR)) {
        return "error";
    } else {
        if (cart.viewCartOnAdd()) {
            return "viewcart";
        } else {
            return "success";
        }
    }
}

From source file:org.finra.herd.service.helper.HerdHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance spot price is specified The
 * definition should be valid because spot price is allowed when max search price is not specified.
 *///  w  w  w .  ja  v a 2s  .c  o m
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterSpotPriceSpecified() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances().setInstanceSpotPrice(BigDecimal.ONE);

    try {
        herdHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
    } catch (Exception e) {
        fail("expected no exception, but " + e.getClass() + " was thrown. " + e);
    }
}

From source file:org.egov.wtms.web.controller.application.MeterReadingController.java

private BigDecimal calculateDemandWithRecursiveAmount(final UsageSlab usageSlab,
        final MeteredRatesDetail meteredRatesDetail, final BigDecimal numberOfUnitsPerMonth) {
    BigDecimal totalAmount = BigDecimal.ZERO;
    BigDecimal amtValue;/*w  w w .jav a 2s.c o m*/
    BigDecimal amount1;
    BigDecimal amount2;
    if (meteredRatesDetail.getFlatAmount() != null && meteredRatesDetail.getFlatAmount() != 0
            && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) {
        amtValue = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume()))
                .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor())
                        .setScale(0, BigDecimal.ROUND_HALF_UP));
        totalAmount = BigDecimal.valueOf(meteredRatesDetail.getFlatAmount())
                .add(amtValue.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount())));
    } else if (meteredRatesDetail.getRateAmount() != null && meteredRatesDetail.getRateAmount() != 0
            && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) {
        amount1 = BigDecimal.valueOf(usageSlab.getFromVolume()).subtract(BigDecimal.ONE)
                .multiply(BigDecimal.valueOf(meteredRatesDetail.getRateAmount()));
        amount2 = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume()))
                .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor()), 0,
                        BigDecimal.ROUND_HALF_UP);
        amtValue = amount2.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount())).setScale(0,
                BigDecimal.ROUND_HALF_UP);
        totalAmount = amount1.add(amtValue);
    }
    return totalAmount;
}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * Calculate delivery amount according to shipment sla cost and items in particular delivery.
 *
 * @param order    order/*from  www  . j  ava 2  s .c o  m*/
 * @param delivery delivery
 * @param payment  payment
 */
private void fillPaymentAmount(final CustomerOrder order, final CustomerOrderDelivery delivery,
        final Payment payment) {
    BigDecimal rez = BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE);
    PaymentLine shipmentLine = null;
    for (PaymentLine paymentLine : payment.getOrderItems()) {
        if (paymentLine.isShipment()) {
            shipmentLine = paymentLine;
        } else {
            // unit price already includes item level promotions
            rez = rez.add(paymentLine.getQuantity().multiply(paymentLine.getUnitPrice())
                    .setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP));
        }
    }
    if (order.isPromoApplied()) {
        // work out the percentage of order level promotion per delivery

        // work out the real sub total using item promotional prices
        // DO NOT use the order.getListPrice() as this is the list price in catalog and we calculate
        // promotions against sale price
        BigDecimal orderTotalList = BigDecimal.ZERO;
        for (final CustomerOrderDet detail : order.getOrderDetail()) {
            orderTotalList = orderTotalList.add(detail.getQty().multiply(detail.getGrossPrice())
                    .setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP));
        }

        final BigDecimal orderTotal = order.getGrossPrice();
        // take the list price (sub total of items using list price)
        final BigDecimal discount = orderTotalList.subtract(orderTotal).divide(orderTotalList, 10,
                RoundingMode.HALF_UP);
        // scale delivery items total in accordance with order level discount percentage
        rez = rez.multiply(BigDecimal.ONE.subtract(discount)).setScale(Constants.DEFAULT_SCALE,
                BigDecimal.ROUND_HALF_UP);
    }
    if (shipmentLine != null) {
        // shipping price already includes shipping level promotions
        rez = rez.add(shipmentLine.getUnitPrice()).setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP);
    }
    payment.setPaymentAmount(rez);
    payment.setOrderCurrency(order.getCurrency());
    payment.setOrderLocale(order.getLocale());
}

From source file:org.finra.dm.service.helper.DmHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance spot price is specified The
 * definition should be valid because spot price is allowed when max search price is not specified.
 *//* w w w  .j  a  va 2s . c  om*/
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterSpotPriceSpecified() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances().setInstanceSpotPrice(BigDecimal.ONE);

    try {
        dmHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
    } catch (Exception e) {
        fail("expected no exception, but " + e.getClass() + " was thrown. " + e);
    }
}

From source file:org.finra.herd.service.helper.HerdHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance max search price is
 * specified The definition should be valid because max search price is allowed when no instance spot price is specified.
 *///from w  ww  .  j  a v  a  2s .  c o  m
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterMaxSearchPriceSpecified() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances()
            .setInstanceMaxSearchPrice(BigDecimal.ONE);

    try {
        herdHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
    } catch (Exception e) {
        fail("expected no exception, but " + e.getClass() + " was thrown. " + e);
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The base of the natural logarithm.//w  w w .  j  a  v a 2 s  .co  m
 *
 * @param mc the required precision of the result
 * @return exp(1) = 2.71828....
 */
static public BigDecimal exp(final MathContext mc) {
    /* look it up if possible */
    if (mc.getPrecision() < E.precision()) {
        return E.round(mc);
    } else {
        /* Instantiate a 1.0 with the requested pseudo-accuracy
         * and delegate the computation to the public method above.
         */
        BigDecimal uni = scalePrec(BigDecimal.ONE, mc.getPrecision());
        return exp(uni);
    }
}