Example usage for java.math BigDecimal toString

List of usage examples for java.math BigDecimal toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns the string representation of this BigDecimal , using scientific notation if an exponent is needed.

Usage

From source file:org.kuali.kpme.tklm.time.batch.ClockedInEmployeeJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    //Get Configuration Settings
    BigDecimal hourLimit = getHourLimit();
    String jobAction = getJobAction();
    String batchJobPrincipalId = BatchJobUtil.getBatchUserPrincipalId();

    // code to send one email per approver
    // Map<String, Map<String, String>> notificationMap = new HashMap<String, Map<String, String>>();

    DateTime asOfDate = new LocalDate().toDateTimeAtStartOfDay();
    List<CalendarEntry> calendarEntries = HrServiceLocator.getCalendarEntryService()
            .getCurrentCalendarEntriesNeedsScheduled(30, asOfDate);

    for (CalendarEntry calendarEntry : calendarEntries) {
        Calendar calendar = HrServiceLocator.getCalendarService().getCalendar(calendarEntry.getHrCalendarId());
        if (StringUtils.equals(calendar.getCalendarTypes(), "Pay")) {
            DateTime beginDate = calendarEntry.getBeginPeriodFullDateTime();
            DateTime endDate = calendarEntry.getEndPeriodFullDateTime();

            List<TimesheetDocumentHeader> timesheetDocumentHeaders = TkServiceLocator
                    .getTimesheetDocumentHeaderService().getDocumentHeaders(beginDate, endDate);

            for (TimesheetDocumentHeader timesheetDocumentHeader : timesheetDocumentHeaders) {
                String principalId = timesheetDocumentHeader.getPrincipalId();
                List<Assignment> assignments = HrServiceLocator.getAssignmentService()
                        .getAllAssignmentsByCalEntryForTimeCalendar(principalId, calendarEntry);
                for (Assignment assignment : assignments) {
                    String groupKeyCode = assignment.getGroupKeyCode();
                    String jobNumber = String.valueOf(assignment.getJobNumber());
                    String workArea = String.valueOf(assignment.getWorkArea());
                    String task = String.valueOf(assignment.getTask());
                    ClockLog lastClockLog = TkServiceLocator.getClockLogService().getLastClockLog(groupKeyCode,
                            principalId, jobNumber, workArea, task, calendarEntry);
                    if (lastClockLog != null
                            && TkConstants.ON_THE_CLOCK_CODES.contains(lastClockLog.getClockAction())) {
                        DateTime lastClockLogDateTime = lastClockLog.getClockDateTime();
                        DateTime currentDate = new DateTime();

                        Period p = new Period(lastClockLogDateTime, currentDate);
                        BigDecimal hoursBetween = new BigDecimal(p.getHours());
                        BigDecimal dayHours = new BigDecimal(p.getDays() * 24);
                        hoursBetween = hoursBetween.add(dayHours);

                        if (hoursBetween.compareTo(hourLimit) > 0) {
                            if (jobAction.equals("NOTIFY")) {

                                //code to send one notification per employee to all approvers of employee
                                for (Person approver : getApprovers(assignment.getWorkArea())) {
                                    EntityNamePrincipalName employee = KimApiServiceLocator.getIdentityService()
                                            .getDefaultNamesForPrincipalId(principalId);
                                    String approverSubject = "Employee Clocked In Over " + hourLimit.toString()
                                            + " Hours Notification";
                                    StringBuilder approverNotification = new StringBuilder();
                                    approverNotification.append(employee.getPrincipalName() + " (" + principalId
                                            + ") has been clocked in since ");
                                    SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM d yyyy HH:mm a");
                                    String dateTime = sdf.format(
                                            new java.sql.Date(lastClockLog.getClockDateTime().getMillis()));
                                    approverNotification.append(dateTime);
                                    approverNotification.append(
                                            " for work area " + assignment.getWorkAreaObj().getDescription());
                                    HrServiceLocator.getKPMENotificationService().sendNotification(
                                            approverSubject, approverNotification.toString(),
                                            approver.getPrincipalId());
                                }/*from w w w.j  a  v a  2  s.  c  o  m*/

                                /* Code to send one email per approver - Create notification
                                Map<String, String> hourInfo = new HashMap<String, String>();
                                hourInfo.put(principalId, hoursBetween.toString());
                                for (Person person : getApprovers(lastClockLog.getWorkArea())) {
                                    if (notificationMap.containsKey(person.getPrincipalId())) {
                                notificationMap.get(person.getPrincipalId()).put(principalId, hoursBetween.toString());
                                    } else {
                                notificationMap.put(person.getPrincipalId(), hourInfo);
                                    }
                                } */
                            } else if (jobAction.equals("CLOCK_OUT")) {
                                //Clock User Out
                                ClockLog clockOut = TkServiceLocator.getClockLogService().processClockLog(
                                        principalId, timesheetDocumentHeader.getDocumentId(), currentDate,
                                        assignment, calendarEntry, TKUtils.getIPNumber(),
                                        currentDate.toLocalDate(), "CO", true, batchJobPrincipalId);

                                TkServiceLocator.getClockLogService().saveClockLog(clockOut);

                                // Notify User
                                String employeeSubject = "You have been clocked out of "
                                        + assignment.getAssignmentDescription();
                                StringBuilder employeeNotification = new StringBuilder();
                                employeeNotification.append(
                                        "You have been Clocked out of " + assignment.getAssignmentDescription()
                                                + " on " + clockOut.getClockDateTime());
                                HrServiceLocator.getKPMENotificationService().sendNotification(employeeSubject,
                                        employeeNotification.toString(), principalId);

                                //add Note to time sheet
                                Note.Builder builder = Note.Builder
                                        .create(timesheetDocumentHeader.getDocumentId(), batchJobPrincipalId);
                                builder.setCreateDate(new DateTime());
                                builder.setText("Clock out from " + assignment.getAssignmentDescription()
                                        + " on " + clockOut.getClockDateTime()
                                        + " was initiated by the Clocked In Employee Batch Job");
                                KewApiServiceLocator.getNoteService().createNote(builder.build());
                            }

                        }
                    }
                }
            }
        }
    }

    /* code to send one email per approver
    for (Map.Entry<String, Map<String, String>> approverEntry : notificationMap.entrySet()) {
    String subject = "Users clocked in over " + hourLimit.toString() + " hours";
    StringBuilder notification = new StringBuilder();
    notification.append("The following users have been clocked in for over " + hourLimit.toString() + " hours:");
    notification.append(SystemUtils.LINE_SEPARATOR);
    for (Map.Entry<String, String> employeeEntry : approverEntry.getValue().entrySet()) {
        notification.append(KimApiServiceLocator.getPersonService().getPerson(employeeEntry.getKey()).getPrincipalName());
        notification.append(" (" + employeeEntry.getKey() + ") : " + employeeEntry.getValue() + " hours");
        notification.append(SystemUtils.LINE_SEPARATOR);
    }
    HrServiceLocator.getKPMENotificationService().sendNotification(subject, notification.toString(), approverEntry.getKey());
    }
    */

}

From source file:org.egov.egf.commons.EgovCommon.java

/**
 * @description -This method returns the number of payments, the total payment amount made, department wise as on a particular
 * date for a list of ProjectCode ids that is passed. NOTE - ASSUMPTION IS EJVs don't have partial payments and CJVs have only
 * 1 project code on debit side./*from   ww w.  j a v a 2 s  .c  o  m*/
 * @param entityList - Integer list containing ProjectCode ids.
 * @param asOnDate - The payments are considered from the beginning to asOnDate. Only fully approved payments are considered.
 * (including asOnDate)
 * @return -A Map containing the total count and total amount department wise. keys are 'count' , 'amount', 'department'
 * @throws ApplicationException - If anyone of the parameters is null or the ProjectCode ids list passed is empty. - If any id
 * passed is wrong.
 */
public Map<String, String> getPaymentInfoforProjectCodeByDepartment(final List<Long> projectCodeIdList,
        final Date asOnDate) throws ApplicationException {
    if (projectCodeIdList == null || projectCodeIdList.size() == 0)
        throw new ApplicationException("ProjectCode Id list is null or empty");
    if (asOnDate == null)
        throw new ApplicationException("asOnDate is null");
    final String strAsOnDate = Constants.DDMMYYYYFORMAT1.format(asOnDate);
    final Map<String, String> result = new HashMap<String, String>();

    final List<String> commaSeperatedEntitiesList = new ArrayList<String>();
    final List<List<Long>> limitedEntityList = new ArrayList<List<Long>>();
    String commaSeperatedEntities = "";
    List<Long> tempEntityIdList = new ArrayList<Long>();
    if (LOGGER.isDebugEnabled())
        LOGGER.debug(" Size of entityIdList-" + projectCodeIdList.size() + " asOnDate - " + asOnDate);
    Long entityId;
    // In sql query, if in list contains more than 1000 elements, it may
    // fail.Hence, we start splitting the list passed into smaller lists of sizes less than 1000.
    for (int i = 0; i < projectCodeIdList.size(); i++) {
        entityId = projectCodeIdList.get(i);
        commaSeperatedEntities = commaSeperatedEntities + entityId + ",";
        tempEntityIdList.add(entityId);
        if (i != 0 && i % 998 == 0 || i == projectCodeIdList.size() - 1) {
            commaSeperatedEntitiesList
                    .add(commaSeperatedEntities.substring(0, commaSeperatedEntities.length() - 1));
            limitedEntityList.add(tempEntityIdList);
            commaSeperatedEntities = "";
            tempEntityIdList = new ArrayList<Long>();
        }
    }

    /*
     * String validationQuery =
     * "SELECT detailkey FROM accountdetailkey WHERE detailtypeid= (SELECT id FROM accountdetailtype " +
     * "WHERE name ='PROJECTCODE' AND description='PROJECTCODE' ) and ( detailkey in ("; List<BigDecimal> dbEntIdList = new
     * ArrayList<BigDecimal>(); boolean isPresent; List<Long> incorrectEntityIds = new ArrayList<Long>(); String
     * dbEntIdQuery=""; if(LOGGER.isDebugEnabled()) LOGGER.debug(" Validation Starts "); for (int i = 0; i <
     * commaSeperatedEntitiesList.size(); i++) { isPresent = false; dbEntIdQuery = validationQuery +
     * commaSeperatedEntitiesList.get(i); if(i!=0) dbEntIdQuery=dbEntIdQuery+ ") or detailkey in(";
     * if(LOGGER.isDebugEnabled()) LOGGER.debug(i + ":dbEntIdQuery- " + dbEntIdQuery);
     * if(i==commaSeperatedEntitiesList.size()-1) dbEntIdQuery=dbEntIdQuery+ ")) order by detailkey "; }
     * if(LOGGER.isDebugEnabled()) LOGGER.debug("Final Query- " + dbEntIdQuery); dbEntIdList = (List<BigDecimal>)
     * persistenceService.getSession().createSQLQuery(dbEntIdQuery).list(); if (dbEntIdList != null && dbEntIdList.size() !=
     * limitedEntityList.size()) { for (int i = 0; i < commaSeperatedEntitiesList.size(); i++) { for (Long entId :
     * limitedEntityList.get(i)) { isPresent = false; for (BigDecimal dbEntId : dbEntIdList) { if (dbEntId.longValue() ==
     * entId.longValue()) { isPresent = true; break; } } if (!isPresent) { incorrectEntityIds.add(entId); } } } } if
     * (incorrectEntityIds.size() != 0) throw new ApplicationException("Incorrect detail key Ids - "+ incorrectEntityIds);
     * if(LOGGER.isDebugEnabled()) LOGGER.debug(" Validation Succeded in method..");
     */
    String qryForExpense = "";
    String qryForNonExpense = "";
    final BigDecimal totalExpensePaymentAmount = BigDecimal.ZERO;
    String deptName = null;
    List<Object[]> objForExpense;
    List<Object[]> objForNonExpense;
    BigDecimal tempAmountObj = BigDecimal.ZERO;

    boolean ifDeptExist = false;
    for (int i = 0; i < commaSeperatedEntitiesList.size(); i++) {
        qryForExpense = getPaymentAmountByDept(commaSeperatedEntitiesList.get(i), strAsOnDate, true);
        qryForNonExpense = getPaymentAmountByDept(commaSeperatedEntitiesList.get(i), strAsOnDate, false);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(i + ": qryForExpense- " + qryForExpense);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(i + ": qryForNonExpense- " + qryForNonExpense);
        objForExpense = persistenceService.getSession().createSQLQuery(qryForExpense).list();
        objForNonExpense = persistenceService.getSession().createSQLQuery(qryForNonExpense).list();
        if (objForExpense != null && objForExpense.size() != 0) {
            tempAmountObj = new BigDecimal(objForExpense.get(0)[0].toString());
            deptName = objForExpense.get(0)[1].toString();
            ifDeptExist = result.containsValue(deptName);
            if (ifDeptExist) {
                result.put(deptName, totalExpensePaymentAmount.add(tempAmountObj).toString());
                result.put("departmentname", deptName);
            } else {
                result.put(deptName, tempAmountObj.toString());
                result.put("departmentname", deptName);
            }
        }
        ifDeptExist = false;
        if (objForNonExpense != null && objForNonExpense.size() != 0) {
            tempAmountObj = new BigDecimal(objForNonExpense.get(0)[0].toString());
            deptName = objForNonExpense.get(0)[1].toString();
            ifDeptExist = result.containsValue(deptName);
            if (ifDeptExist) {
                result.put(deptName, totalExpensePaymentAmount.add(tempAmountObj).toString());
                result.put("departmentname", deptName);
            } else {
                result.put(deptName, tempAmountObj.toString());
                result.put("departmentname", deptName);
            }

        }
    }
    return result;
}

From source file:org.ofbiz.accounting.thirdparty.verisign.PayflowPro.java

/**
 * Authorize credit card payment service. Service wrapper around PayFlow Pro API.
 * @param dctx Service Engine DispatchContext.
 * @param context Map context of parameters.
 * @return Response map, including RESPMSG, and RESULT keys.
 *//*ww w .j a v a 2s  .  co m*/
public static Map<String, Object> ccProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    String orderId = (String) context.get("orderId");
    String cvv2 = (String) context.get("cardSecurityCode");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue party = (GenericValue) context.get("billToParty");
    GenericValue cc = (GenericValue) context.get("creditCard");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    GenericValue ps = (GenericValue) context.get("billingAddress");
    String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
    String configString = (String) context.get("paymentConfig");

    if (configString == null) {
        configString = "payment.properties";
    }

    boolean isPayPal = false;
    // Are we doing a cc or a paypal payment?
    if ("EXT_PAYPAL".equals(paymentPref.getString("paymentMethodTypeId"))) {
        isPayPal = true;
    }

    Map<String, String> data = FastMap.newInstance();

    boolean isReAuth = false;
    if (isPayPal) {
        data.put("TRXTYPE", "A");
        data.put("TENDER", "P");
        data.put("ORIGID", payPalPaymentMethod.getString("transactionId"));
    } else {
        if (authTrans == null) {
            authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
        }

        // set the orderId as comment1 so we can query in PF Manager
        data.put("COMMENT1", orderId);
        data.put("PONUM", orderId);
        data.put("CUSTCODE", party.getString("partyId"));

        // transaction type
        if (comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "preAuth", configString,
                "payment.verisign.preAuth", "Y")) {
            data.put("TRXTYPE", "A");
            // only support re-auth for auth types; sale types don't do it
            if (authTrans != null) {
                String refNum = authTrans.getString("referenceNum");
                data.put("ORIGID", refNum);
                isReAuth = true;
            }
        } else {
            data.put("TRXTYPE", "S");
        }

        // credit card tender
        data.put("TENDER", "C");

        // card security code
        if (UtilValidate.isNotEmpty(cvv2)) {
            data.put("CVV2", cvv2);
        }

        // get the payment information
        data.put("ACCT", cc.getString("cardNumber"));

        // name on card
        String name = cc.getString("firstNameOnCard") + " " + cc.getString("lastNameOnCard");
        data.put("FIRSTNAME", cc.getString("firstNameOnCard"));
        data.put("LASTNAME", cc.getString("lastNameOnCard"));
        data.put("COMMENT2", name);
        if (cc.get("expireDate") != null) {
            String exp = cc.getString("expireDate");
            String expDate = exp.substring(0, 2);

            expDate = expDate + exp.substring(exp.length() - 2);
            data.put("EXPDATE", expDate);
        }

        // gather the address info
        if (ps != null) {
            String street = ps.getString("address1")
                    + ((UtilValidate.isNotEmpty(ps.getString("address2"))) ? " " + ps.getString("address2")
                            : "");
            data.put("STREET" + "[" + street.length() + "]", street);
            data.put("ZIP", ps.getString("postalCode"));
        }
    }

    // set the amount
    data.put("AMT", processAmount.toString());

    PayflowAPI pfp = init(delegator, paymentGatewayConfigId, configString, context);

    // get the base params
    StringBuilder params = makeBaseParams(delegator, paymentGatewayConfigId, configString);

    // parse the context parameters
    params.append("&").append(parseContext(data));

    // transmit the request
    //if (Debug.verboseOn()) Debug.logVerbose("Sending to Verisign: " + params.toString(), module);
    String resp;
    if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString,
            "payment.verisign.enable_transmit", "false")) {
        resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
    } else {
        resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("Response from Verisign: " + resp, module);
    }
    if (isPayPal) {
        // Attach the avs info returned in doExpressCheckout and stored in PayPalPaymentMethod
        resp += "&AVSADDR=" + payPalPaymentMethod.getString("avsAddr") + "&AVSZIP="
                + payPalPaymentMethod.getString("avsZip");
    }

    // check the response
    Map<String, Object> result = ServiceUtil.returnSuccess();
    parseAuthResponse(delegator, paymentGatewayConfigId, resp, result, configString, isReAuth, isPayPal);
    result.put("processAmount", processAmount);
    return result;
}

From source file:org.apache.ofbiz.accounting.thirdparty.verisign.PayflowPro.java

/**
 * Authorize credit card payment service. Service wrapper around PayFlow Pro API.
 * @param dctx Service Engine DispatchContext.
 * @param context Map context of parameters.
 * @return Response map, including RESPMSG, and RESULT keys.
 *///  w w w  . jav a 2s.c  o m
public static Map<String, Object> ccProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    String orderId = (String) context.get("orderId");
    String cvv2 = (String) context.get("cardSecurityCode");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue party = (GenericValue) context.get("billToParty");
    GenericValue cc = (GenericValue) context.get("creditCard");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    GenericValue ps = (GenericValue) context.get("billingAddress");
    String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
    String configString = (String) context.get("paymentConfig");

    if (configString == null) {
        configString = "payment.properties";
    }

    boolean isPayPal = false;
    // Are we doing a cc or a paypal payment?
    if ("EXT_PAYPAL".equals(paymentPref.getString("paymentMethodTypeId"))) {
        isPayPal = true;
    }

    Map<String, String> data = new HashMap<String, String>();

    boolean isReAuth = false;
    if (isPayPal) {
        data.put("TRXTYPE", "A");
        data.put("TENDER", "P");
        data.put("ORIGID", payPalPaymentMethod.getString("transactionId"));
    } else {
        if (authTrans == null) {
            authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
        }

        // set the orderId as comment1 so we can query in PF Manager
        data.put("COMMENT1", orderId);
        data.put("PONUM", orderId);
        data.put("CUSTCODE", party.getString("partyId"));

        // transaction type
        if (comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "preAuth", configString,
                "payment.verisign.preAuth", "Y")) {
            data.put("TRXTYPE", "A");
            // only support re-auth for auth types; sale types don't do it
            if (authTrans != null) {
                String refNum = authTrans.getString("referenceNum");
                data.put("ORIGID", refNum);
                isReAuth = true;
            }
        } else {
            data.put("TRXTYPE", "S");
        }

        // credit card tender
        data.put("TENDER", "C");

        // card security code
        if (UtilValidate.isNotEmpty(cvv2)) {
            data.put("CVV2", cvv2);
        }

        // get the payment information
        data.put("ACCT", cc.getString("cardNumber"));

        // name on card
        String name = cc.getString("firstNameOnCard") + " " + cc.getString("lastNameOnCard");
        data.put("FIRSTNAME", cc.getString("firstNameOnCard"));
        data.put("LASTNAME", cc.getString("lastNameOnCard"));
        data.put("COMMENT2", name);
        if (cc.get("expireDate") != null) {
            String exp = cc.getString("expireDate");
            String expDate = exp.substring(0, 2);

            expDate = expDate + exp.substring(exp.length() - 2);
            data.put("EXPDATE", expDate);
        }

        // gather the address info
        if (ps != null) {
            String street = ps.getString("address1")
                    + ((UtilValidate.isNotEmpty(ps.getString("address2"))) ? " " + ps.getString("address2")
                            : "");
            data.put("STREET" + "[" + street.length() + "]", street);
            data.put("ZIP", ps.getString("postalCode"));
        }
    }

    // set the amount
    data.put("AMT", processAmount.toString());

    PayflowAPI pfp = init(delegator, paymentGatewayConfigId, configString, context);

    // get the base params
    StringBuilder params = makeBaseParams(delegator, paymentGatewayConfigId, configString);

    // parse the context parameters
    params.append("&").append(parseContext(data));

    // transmit the request
    //if (Debug.verboseOn()) Debug.logVerbose("Sending to Verisign: " + params.toString(), module);
    String resp;
    if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString,
            "payment.verisign.enable_transmit", "false")) {
        resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
    } else {
        resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("Response from Verisign: " + resp, module);
    }
    if (isPayPal) {
        // Attach the avs info returned in doExpressCheckout and stored in PayPalPaymentMethod
        resp += "&AVSADDR=" + payPalPaymentMethod.getString("avsAddr") + "&AVSZIP="
                + payPalPaymentMethod.getString("avsZip");
    }

    // check the response
    Map<String, Object> result = ServiceUtil.returnSuccess();
    parseAuthResponse(delegator, paymentGatewayConfigId, resp, result, configString, isReAuth, isPayPal);
    result.put("processAmount", processAmount);
    return result;
}

From source file:com.salesmanager.core.module.impl.integration.payment.AuthorizeNetTransactionImpl.java

public GatewayTransactionVO refundTransaction(IntegrationKeys keys, IntegrationProperties props,
        MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer, CoreModuleService cis,
        BigDecimal amount) throws TransactionException {

    PostMethod httppost = null;//w ww  .  ja  va2  s.c  om
    try {

        String host = cis.getCoreModuleServiceProdDomain();
        String protocol = cis.getCoreModuleServiceProdProtocol();
        String port = cis.getCoreModuleServiceProdPort();
        String url = cis.getCoreModuleServiceProdEnv();
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            host = cis.getCoreModuleServiceDevDomain();
            protocol = cis.getCoreModuleServiceDevProtocol();
            port = cis.getCoreModuleServiceDevPort();
            url = cis.getCoreModuleServiceDevEnv();
        }

        // parse sent elements required
        AuthorizeNetParsedElements pe = null;
        pe = new AuthorizeNetParsedElements();
        Digester digester = new Digester();
        digester.push(pe);

        digester.addCallMethod("transaction/x_card_num", "setCardnumber", 0);
        digester.addCallMethod("transaction/approvalcode", "setApprovalCode", 0);
        digester.addCallMethod("transaction/x_exp_date", "setExpiration", 0);
        digester.addCallMethod("transaction/x_amount", "setTransactionAmount", 0);
        digester.addCallMethod("transaction/x_card_code", "setCvv", 0);

        Reader reader = new StringReader(trx.getTransactionDetails().getGatewaySentDecrypted().trim());

        digester.parse(reader);

        StringBuffer sb = new StringBuffer();

        // mandatory name/value pairs for all AIM CC transactions
        // as well as some "good to have" values
        sb.append("x_login=").append(keys.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sb.append("x_tran_key=").append(keys.getTransactionKey()).append("&"); // replace
        // with
        // your
        // own
        sb.append("x_version=3.1&");// set to required in the specs

        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sb.append("x_test_request=TRUE&"); // for testing
        }

        sb.append("x_method=CC&");// required, CC or ECHECK
        sb.append("x_type=CREDIT&");

        sb.append("x_card_num=").append(pe.getCardnumber()).append("&");// at
        // least
        // 4
        // last
        // card
        // digit
        sb.append("x_exp_date=").append(pe.getExpiration()).append("&");
        sb.append("x_amount=").append(amount.toString()).append("&");
        if (pe.getCvv() != null) {
            sb.append("x_card_code=").append(pe.getCvv()).append("&");
        }
        sb.append("x_delim_data=TRUE&");
        sb.append("x_delim_char=|&");
        sb.append("x_relay_response=FALSE&");
        sb.append("x_trans_id=").append(trx.getTransactionID()).append("&");

        /** debug **/
        StringBuffer sblog = new StringBuffer();

        // mandatory name/value pairs for all AIM CC transactions
        // as well as some "good to have" values
        sblog.append("x_login=").append(keys.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sblog.append("x_tran_key=").append(keys.getTransactionKey()).append("&"); // replace                                                   // own
        sblog.append("x_version=3.1&");// set to required in the specs
        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sblog.append("x_test_request=TRUE&"); // for testing
        }
        sblog.append("x_method=CC&");// required, CC or ECHECK
        sblog.append("x_type=CREDIT&");
        sblog.append("x_card_num=").append(pe.getCardnumber()).append("&");// at
        // least
        // 4
        // last
        // card
        // digit
        sblog.append("x_exp_date=").append(pe.getExpiration()).append("&");
        sblog.append("x_amount=").append(amount.toString()).append("&");
        if (pe.getCvv() != null) {
            sblog.append("x_card_code=").append(pe.getCvv()).append("&");
        }
        sblog.append("x_delim_data=TRUE&");
        sblog.append("x_delim_char=|&");
        sblog.append("x_relay_response=FALSE&");
        sblog.append("x_trans_id=").append(trx.getTransactionID()).append("&");

        log.debug("Transaction sent -> " + sblog.toString());
        /** debug **/

        // sx builds the xml for persisting local
        StringBuffer sx = new StringBuffer();

        sx.append("<transaction>");
        sx.append("<x_login>").append(keys.getUserid()).append("</x_login>"); // replace
        // with
        // your
        // own
        sx.append("<x_tran_key>").append(keys.getTransactionKey()).append("</x_tran_key>"); // replace with your own
        sx.append("<x_version>3.1</x_version>");// set to required in the
        // specs

        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sx.append("<x_test_request>TRUE</x_test_request>"); // for
            // testing
        }

        sx.append("<x_method>CC</x_method>");// required, CC or ECHECK
        sx.append("<x_type>CREDIT</x_type>");

        // need ccard number
        sx.append("<x_card_num>").append(pe.getCardnumber()).append("</x_card_num>");// at least 4 last card digit
        sx.append("<x_exp_date>").append(pe.getExpiration()).append("</x_exp_date>");
        sx.append("<x_amount>").append(pe.getTransactionAmount()).append("</x_amount>");
        if (pe.getCvv() != null) {
            sx.append("<x_card_code>").append(pe.getCvv()).append("</x_card_code>");
        }

        sx.append("<x_delim_data>TRUE</x_delim_data>");
        sx.append("<x_delim_char>|</x_delim_char>");
        sx.append("<x_relay_response>FALSE</x_relay_response>");
        sx.append("<x_trans_id>").append(trx.getTransactionID()).append("</x_trans_id>");
        sx.append("</transaction>");

        HttpClient client = new HttpClient();

        httppost = new PostMethod(protocol + "://" + host + ":" + port + url);
        RequestEntity entity = new StringRequestEntity(sb.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        String stringresult = null;

        int result = client.executeMethod(httppost);
        if (result != 200) {
            log.error("Communication Error with Authorizenet " + protocol + "://" + host + ":" + port + url);
            throw new Exception(
                    "Communication Error with Authorizenet " + protocol + "://" + host + ":" + port + url);
        }
        stringresult = httppost.getResponseBodyAsString();
        log.debug("AuthorizeNet response " + stringresult);

        StringBuffer appendresult = new StringBuffer().append(order.getTotal()).append("|")
                .append(stringresult);

        // Format to xml
        String finalresult = this.readresponse("|", appendresult.toString());

        pe = new AuthorizeNetParsedElements();
        digester = new Digester();
        digester.push(pe);

        digester.addCallMethod("transaction/transactionid", "setTransactionId", 0);
        digester.addCallMethod("transaction/approvalcode", "setApprovalCode", 0);
        digester.addCallMethod("transaction/responsecode", "setResponseCode", 0);
        digester.addCallMethod("transaction/amount", "setTransactionAmount", 0);
        digester.addCallMethod("transaction/reasontext", "setReasontext", 0);
        digester.addCallMethod("transaction/reasoncode", "setReasonCode", 0);

        reader = new StringReader(finalresult);

        digester.parse(reader);

        pe.setTransactionId(trx.getTransactionDetails().getMerchantPaymentGwOrderid());// BECAUSE NOT RETURNED FROM
        // AUTHORIZE NET !!!!

        return this.parseResponse(PaymentConstants.REFUND, sx.toString(), finalresult, pe, order, amount);

    } catch (Exception e) {
        if (e instanceof TransactionException) {
            throw (TransactionException) e;
        }
        log.error(e);

        TransactionException te = new TransactionException("AuthorizeNet Gateway error ", e);
        te.setErrorcode("01");
        throw te;
    } finally {
        if (httppost != null) {
            httppost.releaseConnection();
        }
    }

}

From source file:org.egov.egf.web.actions.voucher.CommonAction.java

private String getCommaSeperatedListForDesignationNameAndFunctionaryName(final String designationName,
        final String functionaryName) {
    final String qrySQL = "select pos_id from eg_eis_employeeinfo empinfo, eg_designation desg, functionary func   "
            + " where empinfo.functionary_id=func.id and empinfo.DESIGNATIONID=desg.DESIGNATIONID "
            + " and empinfo.isactive=true   " + " and desg.DESIGNATION_NAME like '" + designationName
            + "' and func.NAME like '" + functionaryName + "' ";
    final Query query = persistenceService.getSession().createSQLQuery(qrySQL);
    final List<BigDecimal> result = query.list();
    if (result == null || result.isEmpty())
        throw new ValidationException("",
                "No employee with functionary -" + functionaryName + " and designation - " + designationName);
    final StringBuffer returnListSB = new StringBuffer();
    String commaSeperatedList = "";
    for (final BigDecimal posId : result)
        returnListSB.append(posId.toString() + ",");
    commaSeperatedList = returnListSB.substring(0, returnListSB.length() - 1);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Commo seperated  list - " + commaSeperatedList);
    return commaSeperatedList;
}

From source file:model.experiments.stickyprices.StickyPricesCSVPrinter.java

private static void woodMonopolistSweep(final BigDecimal minimumP, final BigDecimal maximumP,
        final BigDecimal minimumI, final BigDecimal maximumI, final BigDecimal increment,
        final int runsPerParameterCombination) throws IOException {

    CSVWriter writer = new CSVWriter(new FileWriter(Paths.get("runs", "rawdata", "monoSweep.csv").toFile()));
    writer.writeNext(new String[] { "P", "I", "distance", "variance", "success" });

    BigDecimal currentP = minimumP;
    while (currentP.compareTo(maximumP) <= 0) {
        BigDecimal currentI = minimumI;

        while (currentI.compareTo(maximumI) <= 0) {

            SummaryStatistics averageSquaredDistance = new SummaryStatistics();
            SummaryStatistics averageVariance = new SummaryStatistics();
            int successes = 0;

            for (int run = 0; run < runsPerParameterCombination; run++) {

                //create the run
                MacroII macroII = new MacroII(run);
                MonopolistScenario scenario = new MonopolistScenario(macroII);
                macroII.setScenario(scenario);
                //set the demand
                scenario.setDemandIntercept(102);
                scenario.setDemandSlope(2);
                scenario.setDailyWageSlope(1);
                scenario.setDailyWageIntercept(0);
                scenario.setAskPricingStrategy(SimpleFlowSellerPID.class);
                scenario.setWorkersToBeRehiredEveryDay(true);
                scenario.setControlType(
                        MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
                scenario.setBuyerDelay(0);

                //start it and have one step
                macroII.start();//from   w ww. jav a 2s . co m
                macroII.schedule.step(macroII);

                //now set the right parameters
                final SalesDepartment salesDepartment = scenario.getMonopolist()
                        .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                final SimpleFlowSellerPID strategy = new SimpleFlowSellerPID(salesDepartment,
                        currentP.floatValue(), currentI.floatValue(), 0f, 0, salesDepartment.getMarket(),
                        salesDepartment.getRandom().nextInt(100), salesDepartment.getFirm().getModel());
                //  strategy.setInitialPrice(102);
                //start them all at the same price, otherwise you advantage the slow by being so slow initially that they end up being right later

                salesDepartment.setAskPricingStrategy(strategy);

                //and make it learned!
                salesDepartment.setPredictorStrategy(new FixedDecreaseSalesPredictor(2));
                final HumanResources hr = scenario.getMonopolist().getHRs().iterator().next();
                hr.setPredictor(new FixedIncreasePurchasesPredictor(1));

                float totalDistance = 0;
                SummaryStatistics prices = new SummaryStatistics();
                //run the model
                double price = 0;
                double quantity = 0;
                for (int i = 0; i < 1000; i++) {
                    macroII.schedule.step(macroII);
                    price = strategy.getTargetPrice();
                    quantity = salesDepartment.getTodayInflow();
                    totalDistance += Math
                            .pow(Math.min(price - (102 - 2 * quantity), price - (102 - 2 * quantity - 1)), 2);
                    prices.addValue(price);
                }

                //Model over, now compute statistics

                averageSquaredDistance.addValue(Math.sqrt(totalDistance));
                averageVariance.addValue(prices.getVariance());
                if (price <= 68 && price >= 67)
                    successes++;

                //            System.out.println(salesDepartment.getLatestObservation(SalesDataType.LAST_ASKED_PRICE));
                macroII.finish();

            }

            String[] csvLine = new String[5];
            csvLine[0] = currentP.toString();
            csvLine[1] = currentI.toString();
            csvLine[2] = String.valueOf(averageSquaredDistance.getMean());
            csvLine[3] = String.valueOf(averageVariance.getMean());
            csvLine[4] = String.valueOf(successes);
            writer.writeNext(csvLine);
            writer.flush();
            System.out.println(Arrays.toString(csvLine));

            currentI = currentI.add(increment).setScale(2);
            System.out.println();

        }

        currentP = currentP.add(increment).setScale(2);

    }

}

From source file:org.apache.pig.test.TestBuiltin.java

@Test
public void testAVGIntermediate() throws Exception {
    String[] avgTypes = { "AVGIntermediate", "DoubleAvgIntermediate", "LongAvgIntermediate",
            "IntAvgIntermediate", "FloatAvgIntermediate", "BigDecimalAvgIntermediate",
            "BigIntegerAvgIntermediate" };
    for (int k = 0; k < avgTypes.length; k++) {
        EvalFunc<?> avg = evalFuncMap.get(avgTypes[k]);
        String inputType = getInputType(avgTypes[k]);
        Tuple tup = inputMap.get(inputType);
        // The tuple we got above has a bag with input
        // values. Input to the Intermediate.exec() however comes
        // from the map which would put each value and a count of
        // 1 in a tuple and send it down. So lets create a bag with
        // tuples that have two fields - the value and a count 1.
        DataBag bag = (DataBag) tup.get(0);
        DataBag bg = bagFactory.newDefaultBag();
        for (Tuple t : bag) {
            Tuple newTuple = tupleFactory.newTuple(2);
            newTuple.set(0, t.get(0));/* w w w.  ja  v  a 2s.c o  m*/
            if (inputType == "BigDecimal") {
                newTuple.set(1, BigDecimal.ONE);
            } else if (inputType == "BigInteger") {
                newTuple.set(1, BigInteger.ONE);
            } else {
                newTuple.set(1, new Long(1));
            }
            bg.add(newTuple);
        }
        Tuple intermediateInput = tupleFactory.newTuple();
        intermediateInput.append(bg);

        Object output = avg.exec(intermediateInput);

        if (inputType == "Long" || inputType == "Integer" || inputType == "IntegerAsLong") {
            Long l = (Long) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + l + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, getExpected(avgTypes[k]), l);
        } else if (inputType == "BigDecimal") {
            BigDecimal f1 = (BigDecimal) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, ((BigDecimal) getExpected(avgTypes[k])).toPlainString(), f1.toPlainString());
        } else if (inputType == "BigInteger") {
            BigInteger f1 = (BigInteger) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, ((BigInteger) getExpected(avgTypes[k])).toString(), f1.toString());
        } else {
            Double f1 = (Double) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, (Double) getExpected(avgTypes[k]), f1, 0.00001);
        }
        if (inputType == "BigDecimal") {
            BigDecimal f2 = (BigDecimal) ((Tuple) output).get(1);
            assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4",
                    "4", f2.toPlainString());

        } else if (inputType == "BigInteger") {
            BigInteger f2 = (BigInteger) ((Tuple) output).get(1);
            assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4",
                    "4", f2.toString());

        } else {
            Long f2 = (Long) ((Tuple) output).get(1);
            assertEquals(
                    "[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 11", 11,
                    f2.longValue());
        }
    }
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Executes one iteration of the getPositionAsOf test. 
 *
 * @param inSymbol a <code>String</code> value
 * @param inDate a <code>Date</code> value
 * @param inExpectedPosition a <code>BigDecimal</code> value
 * @throws Exception if an unexpected error occurs
 *///from  w w w .  j ava  2 s.  c o m
private void doPositionAsOfTest(String inSymbol, Date inDate, BigDecimal inExpectedPosition) throws Exception {
    StrategyCoordinates strategy = getPositionsStrategy();
    setPropertiesToNull();
    AbstractRunningStrategy.setProperty("positionAsOfDuringStop", "not-empty");
    if (inSymbol != null) {
        AbstractRunningStrategy.setProperty("symbol", inSymbol);
    }
    if (inDate != null) {
        AbstractRunningStrategy.setProperty("date", Long.toString(inDate.getTime()));
    }
    verifyStrategyStartsAndStops(strategy.getName(), getLanguage(), strategy.getFile(), null, null, null);
    // verify expected results
    assertEquals((inExpectedPosition == null ? null : inExpectedPosition.toString()),
            AbstractRunningStrategy.getProperty("positionAsOf"));
    assertNull(AbstractRunningStrategy.getProperty("positionAsOfDuringStop"));
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Executes one iteration of the getCurrencyPositionAsOf test. 
 *
 * @param inSymbol a <code>String</code> value
 * @param inDate a <code>Date</code> value
 * @param inExpectedPosition a <code>BigDecimal</code> value
 * @throws Exception if an unexpected error occurs
 *///from   w w w  . j a  v  a  2  s.c  om
private void doCurrencyPositionAsOfTest(String inSymbol, Date inDate, BigDecimal inExpectedPosition)
        throws Exception {
    StrategyCoordinates strategy = getPositionsStrategy();
    setPropertiesToNull();
    AbstractRunningStrategy.setProperty("currencyPositionAsOfDuringStop", "not-empty");
    if (inSymbol != null) {
        AbstractRunningStrategy.setProperty("symbol", inSymbol);
    }
    if (inDate != null) {
        AbstractRunningStrategy.setProperty("date", Long.toString(inDate.getTime()));
    }
    verifyStrategyStartsAndStops(strategy.getName(), getLanguage(), strategy.getFile(), null, null, null);
    // verify expected results
    assertEquals((inExpectedPosition == null ? null : inExpectedPosition.toString()),
            AbstractRunningStrategy.getProperty("currencyPositionAsOf"));
    assertNull(AbstractRunningStrategy.getProperty("currencyPositionAsOfDuringStop"));
}