Search in sources :

Example 76 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class ContentManagementServices method persistDataResourceAndDataMethod.

public static Map<String, Object> persistDataResourceAndDataMethod(DispatchContext dctx, Map<String, ? extends Object> rcontext) throws GenericServiceException, GenericEntityException, Exception {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, Object> newDrContext = new HashMap<String, Object>();
    GenericValue dataResource = delegator.makeValue("DataResource");
    dataResource.setPKFields(context);
    dataResource.setNonPKFields(context);
    dataResource.setAllFields(context, false, "dr", null);
    context.putAll(dataResource);
    GenericValue electronicText = delegator.makeValue("ElectronicText");
    electronicText.setPKFields(context);
    electronicText.setNonPKFields(context);
    String textData = (String) electronicText.get("textData");
    String dataResourceId = (String) dataResource.get("dataResourceId");
    String dataResourceTypeId = (String) dataResource.get("dataResourceTypeId");
    if (Debug.infoOn()) {
        Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, module);
    }
    // TODO: a temp hack because I don't want to bother with DataResource permissions at this time.
    context.put("skipPermissionCheck", "granted");
    boolean dataResourceExists = true;
    if (UtilValidate.isEmpty(dataResourceId)) {
        dataResourceExists = false;
    } else {
        try {
            GenericValue val = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
            if (val == null) {
                dataResourceExists = false;
            }
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.toString());
        }
    }
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    ModelService dataResourceModel = dispatcher.getDispatchContext().getModelService("updateDataResource");
    Map<String, Object> ctx = dataResourceModel.makeValid(dataResource, ModelService.IN_PARAM);
    newDrContext.putAll(ctx);
    newDrContext.put("userLogin", userLogin);
    newDrContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
    ByteBuffer imageDataBytes = (ByteBuffer) context.get("imageData");
    String mimeTypeId = (String) newDrContext.get("mimeTypeId");
    if (imageDataBytes != null && (mimeTypeId == null || (mimeTypeId.indexOf("image") >= 0) || (mimeTypeId.indexOf("application") >= 0))) {
        mimeTypeId = (String) context.get("_imageData_contentType");
        if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
            String fileName = (String) context.get("_imageData_fileName");
            newDrContext.put("objectInfo", fileName);
        }
        newDrContext.put("mimeTypeId", mimeTypeId);
    }
    if (!dataResourceExists) {
        // Create
        Map<String, Object> thisResult = dispatcher.runSync("createDataResource", newDrContext);
        if (ServiceUtil.isError(thisResult)) {
            throw (new Exception(ServiceUtil.getErrorMessage(thisResult)));
        }
        dataResourceId = (String) thisResult.get("dataResourceId");
        if (Debug.infoOn()) {
            Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, module);
        }
        dataResource = (GenericValue) thisResult.get("dataResource");
        Map<String, Object> fileContext = new HashMap<String, Object>();
        fileContext.put("userLogin", userLogin);
        if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
            if (imageDataBytes != null) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("imageData", imageDataBytes);
                thisResult = dispatcher.runSync("createImage", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        } else if ("SHORT_TEXT".equals(dataResourceTypeId)) {
        } else if ("SURVEY".startsWith(dataResourceTypeId)) {
        } else if ("_FILE".indexOf(dataResourceTypeId) >= 0) {
            Map<String, Object> uploadImage = new HashMap<String, Object>();
            uploadImage.put("userLogin", userLogin);
            uploadImage.put("dataResourceId", dataResourceId);
            uploadImage.put("dataResourceTypeId", dataResourceTypeId);
            uploadImage.put("rootDir", context.get("objectInfo"));
            uploadImage.put("uploadedFile", imageDataBytes);
            uploadImage.put("_uploadedFile_fileName", (String) context.get("_imageData_fileName"));
            uploadImage.put("_uploadedFile_contentType", (String) context.get("_imageData_contentType"));
            thisResult = dispatcher.runSync("attachUploadToDataResource", uploadImage);
            if (ServiceUtil.isError(thisResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
            }
        } else {
            // assume ELECTRONIC_TEXT
            if (UtilValidate.isNotEmpty(textData)) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("textData", textData);
                thisResult = dispatcher.runSync("createElectronicText", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        }
    } else {
        // Update
        Map<String, Object> thisResult = dispatcher.runSync("updateDataResource", newDrContext);
        if (ServiceUtil.isError(thisResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
        }
        Map<String, Object> fileContext = new HashMap<String, Object>();
        fileContext.put("userLogin", userLogin);
        String forceElectronicText = (String) context.get("forceElectronicText");
        if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
            if (imageDataBytes != null || "true".equalsIgnoreCase(forceElectronicText)) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("imageData", imageDataBytes);
                thisResult = dispatcher.runSync("updateImage", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        } else if ("SHORT_TEXT".equals(dataResourceTypeId)) {
        } else if ("SURVEY".startsWith(dataResourceTypeId)) {
        } else if ("_FILE".indexOf(dataResourceTypeId) >= 0) {
            Map<String, Object> uploadImage = new HashMap<String, Object>();
            uploadImage.put("userLogin", userLogin);
            uploadImage.put("dataResourceId", dataResourceId);
            uploadImage.put("dataResourceTypeId", dataResourceTypeId);
            uploadImage.put("rootDir", context.get("objectInfo"));
            uploadImage.put("uploadedFile", imageDataBytes);
            uploadImage.put("_uploadedFile_fileName", (String) context.get("_imageData_fileName"));
            uploadImage.put("_uploadedFile_contentType", (String) context.get("_imageData_contentType"));
            thisResult = dispatcher.runSync("attachUploadToDataResource", uploadImage);
            if (ServiceUtil.isError(thisResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
            }
        } else {
            if (UtilValidate.isNotEmpty(textData) || "true".equalsIgnoreCase(forceElectronicText)) {
                fileContext.put("dataResourceId", dataResourceId);
                fileContext.put("textData", textData);
                thisResult = dispatcher.runSync("updateElectronicText", fileContext);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        }
    }
    result.put("dataResourceId", dataResourceId);
    result.put("drDataResourceId", dataResourceId);
    context.put("dataResourceId", dataResourceId);
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) ByteBuffer(java.nio.ByteBuffer) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) ModelService(org.apache.ofbiz.service.ModelService) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 77 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PayPalServices method getExpressCheckout.

public static Map<String, Object> getExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
        encoder.add("TOKEN", token);
    } else {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale));
    }
    NVPDecoder decoder;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
        cart.addOrderNote(decoder.get("NOTE"));
    }
    if (cart.getUserLogin() == null) {
        try {
            GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "anonymous").queryOne();
            try {
                cart.setUserLogin(userLogin, dispatcher);
            } catch (CartItemModifyException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
        // Check nothing has been set on the anon userLogin either
        partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
        cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
        GenericValue party = null;
        try {
            party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (party == null) {
            partyId = null;
        }
    }
    Map<String, Object> inMap = new HashMap<String, Object>();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
        newParty = true;
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("personalTitle", decoder.get("SALUTATION"));
        inMap.put("firstName", decoder.get("FIRSTNAME"));
        inMap.put("middleName", decoder.get("MIDDLENAME"));
        inMap.put("lastName", decoder.get("LASTNAME"));
        inMap.put("suffix", decoder.get("SUFFIX"));
        try {
            outMap = dispatcher.runSync("createPerson", inMap);
            partyId = (String) outMap.get("partyId");
            cart.setOrderPartyId(partyId);
            cart.getUserLogin().setString("partyId", partyId);
            inMap.clear();
            inMap.put("userLogin", cart.getUserLogin());
            inMap.put("partyId", partyId);
            inMap.put("roleTypeId", "CUSTOMER");
            dispatcher.runSync("createPartyRole", inMap);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")), EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityComparisonOperator.EQUALS, EntityFunction.UPPER(emailAddress))));
        try {
            GenericValue matchingEmail = EntityQuery.use(delegator).from("PartyAndContactMech").where(cond).orderBy("fromDate").filterByDate().queryFirst();
            if (matchingEmail != null) {
                emailContactMechId = matchingEmail.getString("contactMechId");
            } else {
                // No email found so we'll need to create one but first check if it should be PRIMARY or just BILLING
                long primaryEmails = EntityQuery.use(delegator).from("PartyContactWithPurpose").where("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS", "contactMechPurposeTypeId", "PRIMARY_EMAIL").filterByDate("contactFromDate", "contactThruDate", "purposeFromDate", "purposeThruDate").queryCount();
                if (primaryEmails > 0)
                    emailContactPurposeTypeId = "BILLING_EMAIL";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (emailContactMechId == null) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
        inMap.put("emailAddress", emailAddress);
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        // Going to assume PayPal has taken care of this for us
        inMap.put("verified", "Y");
        inMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
            emailContactMechId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);
    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
        inMap.clear();
        if (phoneNumber.startsWith("+")) {
            // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
            String[] phoneNumbers = phoneNumber.split(" ");
            inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
            inMap.put("contactNumber", phoneNumbers[1]);
        } else {
            // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
            inMap.put("countryCode", "1");
            String[] phoneNumbers = phoneNumber.split("-");
            inMap.put("areaCode", phoneNumbers[0]);
            inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
        }
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        try {
            outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
            phoneContactId = (String) outMap.get("contactMechId");
            cart.addContactMech("PHONE_BILLING", phoneContactId);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
        }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = new HashMap<String, Object>();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"), delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put("stateProvinceGeoId", parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
        // We want an exact match only
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(postalMap), EntityCondition.makeCondition(UtilMisc.toMap("attnName", null, "directions", null, "postalCodeExt", null, "postalCodeGeoId", null)), EntityCondition.makeCondition("partyId", partyId)));
        try {
            GenericValue postalMatch = EntityQuery.use(delegator).from("PartyAndPostalAddress").where(cond).orderBy("fromDate").filterByDate().queryFirst();
            if (postalMatch != null) {
                postalContactId = postalMatch.getString("contactMechId");
                List<GenericValue> postalPurposes = EntityQuery.use(delegator).from("PartyContactMechPurpose").where("partyId", partyId, "contactMechId", postalContactId).filterByDate().queryList();
                List<Object> purposeStrings = EntityUtil.getFieldListFromEntityList(postalPurposes, "contactMechPurposeTypeId", false);
                if (UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("SHIPPING_LOCATION")) {
                    needsShippingPurpose = false;
                }
                if (needsBillingPurpose && UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("BILLING_LOCATION")) {
                    needsBillingPurpose = false;
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (postalContactId == null) {
        postalMap.put("userLogin", cart.getUserLogin());
        postalMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
            postalContactId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechId", postalContactId);
        inMap.put("partyId", partyId);
        try {
            if (needsShippingPurpose) {
                inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
            if (needsBillingPurpose) {
                inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
        } catch (GenericServiceException e) {
            // Not the end of the world, we'll carry on
            Debug.logInfo(e.getMessage(), module);
        }
    }
    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    if ("Calculated Offline".equals(shipMethod)) {
        cart.setAllCarrierPartyId("_NA_");
        cart.setAllShipmentMethodTypeId("NO_SHIPPING");
    } else {
        String[] shipMethodSplit = shipMethod.split(" - ");
        cart.setAllCarrierPartyId(shipMethodSplit[0]);
        String shippingMethodTypeDesc = StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
        try {
            GenericValue shipmentMethod = EntityQuery.use(delegator).from("ProductStoreShipmentMethView").where("productStoreId", cart.getProductStoreId(), "partyId", shipMethodSplit[0], "roleTypeId", "CARRIER", "description", shippingMethodTypeDesc).queryFirst();
            cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
        } catch (GenericEntityException e1) {
            Debug.logError(e1, module);
        }
    }
    // Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
        Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
        for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
            cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
        }
    }
    cart.cleanUpShipGroups();
    cart.setAllShippingContactMechId(postalContactId);
    Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
        return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }
    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
        shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
        cho.calcAndAddTax();
    } catch (GeneralException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));
    try {
        outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");
    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, RoundingMode.HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) CartShipInfo(org.apache.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) PayPalException(com.paypal.sdk.exceptions.PayPalException) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Example 78 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PayPalServices method doExpressCheckout.

// Note we're not doing a lot of error checking here as this method is really only used
// to confirm the order with PayPal, the subsequent authorizations will handle any errors
// that may occur.
public static Map<String, Object> doExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    Locale locale = (Locale) context.get("locale");
    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false);
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, RoundingMode.HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, RoundingMode.HALF_UP);
    BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2, RoundingMode.HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());
    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalPaymentSetting, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }
    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
        if (errorMessages.containsKey("10417")) {
            // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
            // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
            boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
            if (retry) {
                context.put("_RETRY_", false);
                return PayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }
    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));
    Map<String, Object> outMap = null;
    try {
        outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
        Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
        return outMap;
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) PayPalException(com.paypal.sdk.exceptions.PayPalException) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) BigDecimal(java.math.BigDecimal) NVPEncoder(com.paypal.sdk.core.nvp.NVPEncoder) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) NVPDecoder(com.paypal.sdk.core.nvp.NVPDecoder) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 79 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PayflowPro method getExpressCheckout.

public static Map<String, Object> getExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    ShoppingCart cart = (ShoppingCart) context.get("cart");
    Locale locale = cart.getLocale();
    GenericValue payPalPaymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, cart.getProductStoreId(), "EXT_PAYPAL", null, true);
    String paymentGatewayConfigId = payPalPaymentSetting.getString("paymentGatewayConfigId");
    String configString = "payment.properties";
    Map<String, String> data = new HashMap<String, String>();
    data.put("TRXTYPE", "O");
    data.put("TENDER", "P");
    data.put("ACTION", "G");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
        data.put("TOKEN", token);
    }
    PayflowAPI pfp = init(delegator, paymentGatewayConfigId, null, context);
    // get the base params
    StringBuilder params = makeBaseParams(delegator, paymentGatewayConfigId, null);
    // 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&PAYERID=" + (new Date()).getTime() + "&RESPMSG=Testing";
    }
    Map<String, String> responseMap = parseResponse(resp);
    if (!"0".equals(responseMap.get("RESULT"))) {
        Debug.logError("A problem occurred while requesting the checkout details from paypal: Result = " + responseMap.get("RESULT") + ", Message = " + responseMap.get("RESPMSG"), module);
        return ServiceUtil.returnError(UtilProperties.getMessage("AccountingErrorUiLabels", "AccountingPayPalCommunicationError", locale));
    }
    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", cart.getOrderPartyId());
    inMap.put("contactMechId", cart.getShippingContactMechId());
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", responseMap.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", responseMap.get("PAYERSTATUS"));
    inMap.put("avsAddr", responseMap.get("AVSADDR"));
    inMap.put("avsZip", responseMap.get("AVSZIP"));
    inMap.put("correlationId", responseMap.get("CORRELATIONID"));
    Map<String, Object> outMap = null;
    try {
        outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");
    cart.clearPayments();
    cart.addPaymentAmount(paymentMethodId, cart.getGrandTotal(), true);
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) PayflowAPI(paypal.payflow.PayflowAPI) Date(java.util.Date) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 80 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class PayPalEvents method payPalIPN.

/**
 * PayPal Call-Back Event
 * @throws IOException
 */
public static String payPalIPN(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Locale locale = UtilHttp.getLocale(request);
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    // get the product store
    GenericValue productStore = ProductStoreWorker.getProductStore(request);
    if (productStore == null) {
        Debug.logError("ProductStore is null", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingMerchantConfiguration", locale));
        return "error";
    }
    // get the payment properties file
    GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), "EXT_PAYPAL", null, true);
    String configString = null;
    String paymentGatewayConfigId = null;
    if (paymentConfig != null) {
        paymentGatewayConfigId = paymentConfig.getString("paymentGatewayConfigId");
        configString = paymentConfig.getString("paymentPropertiesPath");
    }
    if (configString == null) {
        configString = "payment.properties";
    }
    // get the confirm URL
    String confirmUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "confirmUrl", configString, "payment.paypal.confirm");
    // get the redirect URL
    String redirectUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "redirectUrl", configString, "payment.paypal.redirect");
    if (UtilValidate.isEmpty(confirmUrl) || UtilValidate.isEmpty(redirectUrl)) {
        Debug.logError("Payment properties is not configured properly, no confirm URL defined!", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingMerchantConfiguration", locale));
        return "error";
    }
    // first verify this is valid from PayPal
    Map<String, Object> parametersMap = UtilHttp.getParameterMap(request);
    parametersMap.put("cmd", "_notify-validate");
    // send off the confirm request
    String confirmResp = null;
    String str = UtilHttp.urlEncodeArgs(parametersMap);
    URL u = new URL(redirectUrl);
    URLConnection uc = u.openConnection();
    uc.setDoOutput(true);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    try (BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream(), "UTF-8"))) {
        pw.println(str);
        confirmResp = in.readLine();
        Debug.logError("PayPal Verification Response: " + confirmResp, module);
    } catch (IOException e) {
        Debug.logError(e, "Problems sending verification message.", module);
    }
    Debug.logInfo("Got verification from PayPal, processing..", module);
    boolean verified = false;
    for (String name : parametersMap.keySet()) {
        String value = request.getParameter(name);
        Debug.logError("### Param: " + name + " => " + value, module);
        if (UtilValidate.isNotEmpty(name) && "payer_status".equalsIgnoreCase(name) && UtilValidate.isNotEmpty(value) && "verified".equalsIgnoreCase(value)) {
            verified = true;
        }
    }
    if (!verified) {
        Debug.logError("###### PayPal did not verify this request, need investigation!", module);
    }
    // get the system user
    GenericValue userLogin = null;
    try {
        userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot get UserLogin for: system; cannot continue", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingAuthenticationUser", locale));
        return "error";
    }
    // get the orderId
    String orderId = request.getParameter("invoice");
    // get the order header
    GenericValue orderHeader = null;
    if (UtilValidate.isNotEmpty(orderId)) {
        try {
            orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot get the order header for order: " + orderId, module);
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingOrderHeader", locale));
            return "error";
        }
    } else {
        Debug.logError("PayPal did not callback with a valid orderId!", module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.noValidOrderIdReturned", locale));
        return "error";
    }
    if (orderHeader == null) {
        Debug.logError("Cannot get the order header for order: " + orderId, module);
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.problemsGettingOrderHeader", locale));
        return "error";
    }
    // get the transaction status
    String paymentStatus = request.getParameter("payment_status");
    // attempt to start a transaction
    boolean okay = true;
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        if ("Completed".equals(paymentStatus)) {
            okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        } else if ("Failed".equals(paymentStatus) || "Denied".equals(paymentStatus)) {
            okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
        }
        if (okay) {
            // set the payment preference
            okay = setPaymentPreferences(delegator, dispatcher, userLogin, orderId, request);
        }
    } catch (Exception e) {
        String errMsg = "Error handling PayPal notification";
        Debug.logError(e, errMsg, module);
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, e);
        } catch (GenericTransactionException gte2) {
            Debug.logError(gte2, "Unable to rollback transaction", module);
        }
    } finally {
        if (!okay) {
            try {
                TransactionUtil.rollback(beganTransaction, "Failure in processing PayPal callback", null);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to rollback transaction", module);
            }
        } else {
            try {
                TransactionUtil.commit(beganTransaction);
            } catch (GenericTransactionException gte) {
                Debug.logError(gte, "Unable to commit transaction", module);
            }
        }
    }
    if (okay) {
        // call the email confirm service
        Map<String, String> emailContext = UtilMisc.toMap("orderId", orderId);
        try {
            dispatcher.runSync("sendOrderConfirmation", emailContext);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problems sending email confirmation", module);
        }
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ParseException(java.text.ParseException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BufferedReader(java.io.BufferedReader) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) OutputStreamWriter(java.io.OutputStreamWriter) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) PrintWriter(java.io.PrintWriter)

Aggregations

LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)427 GenericValue (org.apache.ofbiz.entity.GenericValue)356 Delegator (org.apache.ofbiz.entity.Delegator)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)321 Locale (java.util.Locale)296 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)270 HashMap (java.util.HashMap)214 BigDecimal (java.math.BigDecimal)135 GeneralException (org.apache.ofbiz.base.util.GeneralException)87 Timestamp (java.sql.Timestamp)81 LinkedList (java.util.LinkedList)79 IOException (java.io.IOException)59 Map (java.util.Map)51 HttpSession (javax.servlet.http.HttpSession)49 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)28 ModelService (org.apache.ofbiz.service.ModelService)28 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)24 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)23 Security (org.apache.ofbiz.security.Security)20 ByteBuffer (java.nio.ByteBuffer)19