Search in sources :

Example 1 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class DhlConnectException method dhlRateEstimate.

/*
     * Service to obtain a rate estimate from DHL for a shipment. Notes: Only one package per shipment currently supported by DHL ShipIT.
     * If this service returns a null shippingEstimateAmount, then the shipment has not been processed
     */
public static Map<String, Object> dhlRateEstimate(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    // some of these can be refactored
    String carrierPartyId = (String) context.get("carrierPartyId");
    String shipmentMethodTypeId = (String) context.get("shipmentMethodTypeId");
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight");
    if ("NO_SHIPPING".equals(shipmentMethodTypeId)) {
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.put("shippingEstimateAmount", null);
        return result;
    }
    // translate shipmentMethodTypeId to DHL service code
    String dhlShipmentDetailCode = null;
    try {
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("shipmentMethodTypeId", shipmentMethodTypeId, "partyId", carrierPartyId, "roleTypeId", "CARRIER").queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlNoCarrierShipmentMethod", UtilMisc.toMap("carrierPartyId", carrierPartyId, "shipmentMethodTypeId", shipmentMethodTypeId), locale));
        }
        dhlShipmentDetailCode = carrierShipmentMethod.getString("carrierServiceCode");
    } catch (GenericEntityException e) {
        Debug.logError(e, "Failed to get rate estimate: " + e.getMessage(), module);
    }
    String resource = (String) context.get("serviceConfigProps");
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    // shipping credentials (configured in properties)
    String userid = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessUserId", resource, "shipment.dhl.access.userid");
    String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessPassword", resource, "shipment.dhl.access.password");
    String shippingKey = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessShippingKey", resource, "shipment.dhl.access.shippingKey");
    String accountNbr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessAccountNbr", resource, "shipment.dhl.access.accountNbr");
    if ((shippingKey.length() == 0) || (accountNbr.length() == 0)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlGatewayNotAvailable", locale));
    }
    // obtain the ship-to address
    GenericValue shipToAddress = null;
    if (shippingContactMechId != null) {
        try {
            shipToAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", shippingContactMechId).queryOne();
            if (shipToAddress == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUnableFoundShipToAddresss", locale));
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if ((shippableWeight == null) || (shippableWeight.compareTo(BigDecimal.ZERO) <= 0)) {
        String tmpValue = EntityUtilProperties.getPropertyValue(shipmentPropertiesFile, "shipment.default.weight.value", delegator);
        if (tmpValue != null) {
            try {
                shippableWeight = new BigDecimal(tmpValue);
            } catch (Exception e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlDefaultShippableWeightNotConfigured", locale));
            }
        }
    }
    // TODO: if a weight UOM is passed in, use convertUom service to convert it here
    if (shippableWeight.compareTo(BigDecimal.ONE) < 0) {
        Debug.logWarning("DHL Estimate: Weight is less than 1 lb, submitting DHL minimum of 1 lb for estimate.", module);
        shippableWeight = BigDecimal.ONE;
    }
    if (("G".equals(dhlShipmentDetailCode) && shippableWeight.compareTo(new BigDecimal("999")) > 0) || (shippableWeight.compareTo(new BigDecimal("150")) > 0)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlShippableWeightExceed", locale));
    }
    String weight = shippableWeight.toString();
    // create AccessRequest XML doc using FreeMarker template
    String templateName = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "rateEstimateTemplate", resource, "shipment.dhl.template.rate.estimate");
    if (templateName.trim().length() == 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlShipmentTemplateLocationNotFound", locale));
    }
    StringWriter outWriter = new StringWriter();
    Map<String, Object> inContext = new HashMap<String, Object>();
    inContext.put("action", "RateEstimate");
    inContext.put("userid", userid);
    inContext.put("password", password);
    inContext.put("accountNbr", accountNbr);
    inContext.put("shippingKey", shippingKey);
    inContext.put("shipDate", UtilDateTime.nowTimestamp());
    inContext.put("dhlShipmentDetailCode", dhlShipmentDetailCode);
    inContext.put("weight", weight);
    inContext.put("state", shipToAddress.getString("stateProvinceGeoId"));
    // DHL ShipIT API does not accept ZIP+4
    if ((shipToAddress.getString("postalCode") != null) && (shipToAddress.getString("postalCode").length() > 5)) {
        inContext.put("postalCode", shipToAddress.getString("postalCode").substring(0, 5));
    } else {
        inContext.put("postalCode", shipToAddress.getString("postalCode"));
    }
    try {
        ContentWorker.renderContentAsText(dispatcher, templateName, outWriter, inContext, locale, "text/plain", null, null, false);
    } catch (Exception e) {
        Debug.logError(e, "Cannot get DHL Estimate: Failed to render DHL XML Request.", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlShipmentTemplateError", locale));
    }
    String requestString = outWriter.toString();
    if (Debug.verboseOn()) {
        Debug.logVerbose(requestString, module);
    }
    // send the request
    String rateResponseString = null;
    try {
        rateResponseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, resource, locale);
        if (Debug.verboseOn()) {
            Debug.logVerbose(rateResponseString, module);
        }
    } catch (DhlConnectException e) {
        String uceErrMsg = "Error sending DHL request for DHL Service Rate: " + e.toString();
        Debug.logError(e, uceErrMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlShipmentTemplateSendingError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    Document rateResponseDocument = null;
    try {
        rateResponseDocument = UtilXml.readXmlDocument(rateResponseString, false);
        return handleDhlRateResponse(rateResponseDocument, locale);
    } catch (SAXException e2) {
        String excErrMsg = "Error parsing the RatingServiceResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexShipmentTemplateParsingError", UtilMisc.toMap("errorString", e2.toString()), locale));
    } catch (ParserConfigurationException e2) {
        String excErrMsg = "Error parsing the RatingServiceResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexShipmentTemplateParsingError", UtilMisc.toMap("errorString", e2.toString()), locale));
    } catch (IOException e2) {
        String excErrMsg = "Error parsing the RatingServiceResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexShipmentTemplateParsingError", UtilMisc.toMap("errorString", e2.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) IOException(java.io.IOException) Document(org.w3c.dom.Document) BigDecimal(java.math.BigDecimal) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 2 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class FedexConnectException method fedexSubscriptionRequest.

/*
    * Register a Fedex account for shipping by obtaining the meter number
    */
public static Map<String, Object> fedexSubscriptionRequest(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");
    List<Object> errorList = new LinkedList<Object>();
    Boolean replaceMeterNumber = (Boolean) context.get("replaceMeterNumber");
    if (!replaceMeterNumber.booleanValue()) {
        String meterNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessMeterNumber", resource, "shipment.fedex.access.meterNumber");
        if (UtilValidate.isNotEmpty(meterNumber)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexMeterNumberAlreadyExists", UtilMisc.toMap("meterNumber", meterNumber), locale));
        }
    }
    String companyPartyId = (String) context.get("companyPartyId");
    String contactPartyName = (String) context.get("contactPartyName");
    Map<String, Object> result = new HashMap<String, Object>();
    String accountNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessAccountNbr", resource, "shipment.fedex.access.accountNbr");
    if (UtilValidate.isEmpty(accountNumber)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexAccountNumberNotFound", locale));
    }
    if (UtilValidate.isEmpty(contactPartyName)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexContactNameCannotBeEmpty", locale));
    }
    String companyName = null;
    GenericValue postalAddress = null;
    String phoneNumber = null;
    String faxNumber = null;
    String emailAddress = null;
    try {
        // Make sure the company exists
        GenericValue companyParty = EntityQuery.use(delegator).from("Party").where("partyId", companyPartyId).cache().queryOne();
        if (companyParty == null) {
            String errorMessage = "Party with partyId " + companyPartyId + " does not exist";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyDoesNotExists", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        // Get the company name (required by Fedex)
        companyName = PartyHelper.getPartyName(companyParty);
        if (UtilValidate.isEmpty(companyName)) {
            String errorMessage = "Party with partyId " + companyPartyId + " has no name";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyHasNoName", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        // Get the contact information for the company
        List<GenericValue> partyContactDetails = EntityQuery.use(delegator).from("PartyContactDetailByPurpose").where("partyId", companyPartyId).filterByDate(UtilDateTime.nowTimestamp(), "fromDate", "thruDate", "purposeFromDate", "purposeThruDate").queryList();
        // Get the first valid postal address (address1, city, postalCode and countryGeoId are required by Fedex)
        List<EntityCondition> postalAddressConditions = new LinkedList<EntityCondition>();
        postalAddressConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "POSTAL_ADDRESS"));
        postalAddressConditions.add(EntityCondition.makeCondition("address1", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("address1", EntityOperator.NOT_EQUAL, ""));
        postalAddressConditions.add(EntityCondition.makeCondition("city", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("city", EntityOperator.NOT_EQUAL, ""));
        postalAddressConditions.add(EntityCondition.makeCondition("postalCode", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("postalCode", EntityOperator.NOT_EQUAL, ""));
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, null));
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> postalAddresses = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(postalAddressConditions, EntityOperator.AND));
        // Fedex requires USA or Canada addresses to have a state/province ID, so filter out the ones without
        postalAddressConditions.clear();
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.IN, UtilMisc.toList("CAN", "USA")));
        postalAddressConditions.add(EntityCondition.makeCondition("stateProvinceGeoId", EntityOperator.EQUALS, null));
        postalAddresses = EntityUtil.filterOutByCondition(postalAddresses, EntityCondition.makeCondition(postalAddressConditions, EntityOperator.AND));
        postalAddressConditions.clear();
        postalAddressConditions.add(EntityCondition.makeCondition("countryGeoId", EntityOperator.IN, UtilMisc.toList("CAN", "USA")));
        postalAddressConditions.add(EntityCondition.makeCondition("stateProvinceGeoId", EntityOperator.EQUALS, ""));
        postalAddresses = EntityUtil.filterOutByCondition(postalAddresses, EntityCondition.makeCondition(postalAddressConditions, EntityOperator.AND));
        postalAddress = EntityUtil.getFirst(postalAddresses);
        if (UtilValidate.isEmpty(postalAddress)) {
            String errorMessage = "Party with partyId " + companyPartyId + " does not have a current, fully populated postal address";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyHasNotPostalAddress", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        GenericValue countryGeo = EntityQuery.use(delegator).from("Geo").where("geoId", postalAddress.getString("countryGeoId")).cache().queryOne();
        String countryCode = countryGeo.getString("geoCode");
        String stateOrProvinceCode = null;
        // Only add the StateOrProvinceCode element if the address is in USA or Canada
        if ("CA".equals(countryCode) || "US".equals(countryCode)) {
            GenericValue stateProvinceGeo = EntityQuery.use(delegator).from("Geo").where("geoId", postalAddress.getString("stateProvinceGeoId")).cache().queryOne();
            stateOrProvinceCode = stateProvinceGeo.getString("geoCode");
        }
        // Get the first valid primary phone number (required by Fedex)
        List<EntityCondition> phoneNumberConditions = new LinkedList<EntityCondition>();
        phoneNumberConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "TELECOM_NUMBER"));
        phoneNumberConditions.add(EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.EQUALS, "PRIMARY_PHONE"));
        phoneNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, null));
        phoneNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, ""));
        phoneNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, null));
        phoneNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> phoneNumbers = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(phoneNumberConditions, EntityOperator.AND));
        GenericValue phoneNumberValue = EntityUtil.getFirst(phoneNumbers);
        if (UtilValidate.isEmpty(phoneNumberValue)) {
            String errorMessage = "Party with partyId " + companyPartyId + " does not have a current, fully populated primary phone number";
            Debug.logError(errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexCompanyPartyHasNotPrimaryPhoneNumber", UtilMisc.toMap("companyPartyId", companyPartyId), locale));
        }
        phoneNumber = phoneNumberValue.getString("areaCode") + phoneNumberValue.getString("contactNumber");
        // Fedex doesn't want the North American country code
        if (UtilValidate.isNotEmpty(phoneNumberValue.getString("countryCode")) && !("CA".equals(countryCode) || "US".equals(countryCode))) {
            phoneNumber = phoneNumberValue.getString("countryCode") + phoneNumber;
        }
        phoneNumber = phoneNumber.replaceAll("[^+\\d]", "");
        // Get the first valid fax number
        List<EntityCondition> faxNumberConditions = new LinkedList<EntityCondition>();
        faxNumberConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "TELECOM_NUMBER"));
        faxNumberConditions.add(EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.EQUALS, "FAX_NUMBER"));
        faxNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, null));
        faxNumberConditions.add(EntityCondition.makeCondition("areaCode", EntityOperator.NOT_EQUAL, ""));
        faxNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, null));
        faxNumberConditions.add(EntityCondition.makeCondition("contactNumber", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> faxNumbers = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(faxNumberConditions, EntityOperator.AND));
        GenericValue faxNumberValue = EntityUtil.getFirst(faxNumbers);
        if (!UtilValidate.isEmpty(faxNumberValue)) {
            faxNumber = faxNumberValue.getString("areaCode") + faxNumberValue.getString("contactNumber");
            // Fedex doesn't want the North American country code
            if (UtilValidate.isNotEmpty(faxNumberValue.getString("countryCode")) && !("CA".equals(countryCode) || "US".equals(countryCode))) {
                faxNumber = faxNumberValue.getString("countryCode") + faxNumber;
            }
            faxNumber = faxNumber.replaceAll("[^+\\d]", "");
        }
        // Get the first valid email address
        List<EntityCondition> emailConditions = new LinkedList<EntityCondition>();
        emailConditions.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "EMAIL_ADDRESS"));
        emailConditions.add(EntityCondition.makeCondition("infoString", EntityOperator.NOT_EQUAL, null));
        emailConditions.add(EntityCondition.makeCondition("infoString", EntityOperator.NOT_EQUAL, ""));
        List<GenericValue> emailAddresses = EntityUtil.filterByCondition(partyContactDetails, EntityCondition.makeCondition(emailConditions, EntityOperator.AND));
        GenericValue emailAddressValue = EntityUtil.getFirst(emailAddresses);
        if (!UtilValidate.isEmpty(emailAddressValue)) {
            emailAddress = emailAddressValue.getString("infoString");
        }
        // Get the location of the Freemarker (XML) template for the FDXSubscriptionRequest
        String templateLocation = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "templateSubscription", resource, "shipment.fedex.template.subscription.location");
        if (UtilValidate.isEmpty(templateLocation)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateLocationNotFound", UtilMisc.toMap("templateLocation", templateLocation), locale));
        }
        // Populate the Freemarker context
        Map<String, Object> subscriptionRequestContext = new HashMap<String, Object>();
        subscriptionRequestContext.put("AccountNumber", accountNumber);
        subscriptionRequestContext.put("PersonName", contactPartyName);
        subscriptionRequestContext.put("CompanyName", companyName);
        subscriptionRequestContext.put("PhoneNumber", phoneNumber);
        if (UtilValidate.isNotEmpty(faxNumber)) {
            subscriptionRequestContext.put("FaxNumber", faxNumber);
        }
        if (UtilValidate.isNotEmpty(emailAddress)) {
            subscriptionRequestContext.put("EMailAddress", emailAddress);
        }
        subscriptionRequestContext.put("Line1", postalAddress.getString("address1"));
        if (UtilValidate.isNotEmpty(postalAddress.getString("address2"))) {
            subscriptionRequestContext.put("Line2", postalAddress.getString("address2"));
        }
        subscriptionRequestContext.put("City", postalAddress.getString("city"));
        if (UtilValidate.isNotEmpty(stateOrProvinceCode)) {
            subscriptionRequestContext.put("StateOrProvinceCode", stateOrProvinceCode);
        }
        subscriptionRequestContext.put("PostalCode", postalAddress.getString("postalCode"));
        subscriptionRequestContext.put("CountryCode", countryCode);
        StringWriter outWriter = new StringWriter();
        try {
            FreeMarkerWorker.renderTemplate(templateLocation, subscriptionRequestContext, outWriter);
        } catch (Exception e) {
            String errorMessage = "Cannot send Fedex subscription request: Failed to render Fedex XML Subscription Request Template [" + templateLocation + "].";
            Debug.logError(e, errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateError", UtilMisc.toMap("templateLocation", templateLocation, "errorString", e.getMessage()), locale));
        }
        String fDXSubscriptionRequestString = outWriter.toString();
        // Send the request
        String fDXSubscriptionReplyString = null;
        try {
            fDXSubscriptionReplyString = sendFedexRequest(fDXSubscriptionRequestString, delegator, shipmentGatewayConfigId, resource, locale);
            Debug.logInfo("Fedex response for FDXSubscriptionRequest:" + fDXSubscriptionReplyString, module);
        } catch (FedexConnectException e) {
            String errorMessage = "Error sending Fedex request for FDXSubscriptionRequest: " + e.toString();
            Debug.logError(e, errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateSendingError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        Document fDXSubscriptionReplyDocument = null;
        try {
            fDXSubscriptionReplyDocument = UtilXml.readXmlDocument(fDXSubscriptionReplyString, false);
            Debug.logInfo("Fedex response for FDXSubscriptionRequest:" + fDXSubscriptionReplyString, module);
        } catch (SAXException | ParserConfigurationException | IOException e) {
            String errorMessage = "Error parsing the FDXSubscriptionRequest response: " + e.toString();
            Debug.logError(e, errorMessage, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexSubscriptionTemplateParsingError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        Element fedexSubscriptionReplyElement = fDXSubscriptionReplyDocument.getDocumentElement();
        handleErrors(fedexSubscriptionReplyElement, errorList, locale);
        if (UtilValidate.isNotEmpty(errorList)) {
            return ServiceUtil.returnError(errorList);
        }
        String meterNumber = UtilXml.childElementValue(fedexSubscriptionReplyElement, "MeterNumber");
        result.put("meterNumber", meterNumber);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) LinkedList(java.util.LinkedList) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 3 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class UpsConnectException method upsVoidShipment.

public static Map<String, Object> upsVoidShipment(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator, shipmentId, locale);
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsGatewayNotAvailable", locale));
    }
    boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true"));
    String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context);
    File shipmentUpsSaveCertificationFile = null;
    if (shipmentUpsSaveCertificationInfo) {
        shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath);
        if (!shipmentUpsSaveCertificationFile.exists()) {
            shipmentUpsSaveCertificationFile.mkdirs();
        }
    }
    String voidShipmentResponseString = null;
    try {
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale));
        }
        // add ShipmentRouteSegment carrierServiceStatusId, check before all UPS services
        if (!"SHRSCS_CONFIRMED".equals(shipmentRouteSegment.getString("carrierServiceStatusId")) && !"SHRSCS_ACCEPTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentStatusMustBeConfirmedOrAccepted", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale));
        }
        if (UtilValidate.isEmpty(shipmentRouteSegment.getString("trackingIdNumber"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsTrackingIdNumberWasNotSet", locale));
        }
        Document voidShipmentRequestDoc = UtilXml.makeEmptyXmlDocument("VoidShipmentRequest");
        Element voidShipmentRequestElement = voidShipmentRequestDoc.getDocumentElement();
        voidShipmentRequestElement.setAttribute("xml:lang", "en-US");
        // Top Level Element: Request
        Element requestElement = UtilXml.addChildElement(voidShipmentRequestElement, "Request", voidShipmentRequestDoc);
        Element transactionReferenceElement = UtilXml.addChildElement(requestElement, "TransactionReference", voidShipmentRequestDoc);
        UtilXml.addChildElementValue(transactionReferenceElement, "CustomerContext", "Void / 1", voidShipmentRequestDoc);
        UtilXml.addChildElementValue(transactionReferenceElement, "XpciVersion", "1.0001", voidShipmentRequestDoc);
        UtilXml.addChildElementValue(requestElement, "RequestAction", "Void", voidShipmentRequestDoc);
        UtilXml.addChildElementValue(requestElement, "RequestOption", "1", voidShipmentRequestDoc);
        UtilXml.addChildElementValue(voidShipmentRequestElement, "ShipmentIdentificationNumber", shipmentRouteSegment.getString("trackingIdNumber"), voidShipmentRequestDoc);
        String voidShipmentRequestString = null;
        try {
            voidShipmentRequestString = UtilXml.writeXmlDocument(voidShipmentRequestDoc);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the VoidShipmentRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorVoidShipmentRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // create AccessRequest XML doc
        Document accessRequestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, resource);
        String accessRequestString = null;
        try {
            accessRequestString = UtilXml.writeXmlDocument(accessRequestDocument);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the AccessRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorAccessRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // connect to UPS server, send AccessRequest to auth
        // send ShipmentConfirmRequest String
        // get ShipmentConfirmResponse String back
        StringBuilder xmlString = new StringBuilder();
        xmlString.append(accessRequestString);
        xmlString.append(voidShipmentRequestString);
        if (shipmentUpsSaveCertificationInfo) {
            String outFileName = shipmentUpsSaveCertificationPath + "/UpsVoidShipmentRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml";
            try (FileOutputStream fileOut = new FileOutputStream(outFileName)) {
                fileOut.write(xmlString.toString().getBytes(UtilIO.getUtf8()));
                fileOut.flush();
            } catch (IOException e) {
                Debug.logInfo(e, "Could not save UPS XML file: [[[" + xmlString.toString() + "]]] to file: " + outFileName, module);
            }
        }
        try {
            voidShipmentResponseString = sendUpsRequest("Void", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale);
        } catch (UpsConnectException e) {
            String uceErrMsg = "Error sending UPS request for UPS Service Void: " + e.toString();
            Debug.logError(e, uceErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorSendingVoid", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        if (shipmentUpsSaveCertificationInfo) {
            String outFileName = shipmentUpsSaveCertificationPath + "/UpsVoidShipmentResponse" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml";
            try (FileOutputStream fileOut = new FileOutputStream(outFileName)) {
                fileOut.write(voidShipmentResponseString.getBytes(UtilIO.getUtf8()));
                fileOut.flush();
            } catch (IOException e) {
                Debug.logInfo(e, "Could not save UPS XML file: [[[" + xmlString.toString() + "]]] to file: " + outFileName, module);
            }
        }
        Document voidShipmentResponseDocument = null;
        try {
            voidShipmentResponseDocument = UtilXml.readXmlDocument(voidShipmentResponseString, false);
        } catch (SAXException e2) {
            String excErrMsg = "Error parsing the VoidShipmentResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingVoidShipmentResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
        } catch (ParserConfigurationException e2) {
            String excErrMsg = "Error parsing the VoidShipmentResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingVoidShipmentResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
        } catch (IOException e2) {
            String excErrMsg = "Error parsing the VoidShipmentResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingVoidShipmentResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
        }
        return handleUpsVoidShipmentResponse(voidShipmentResponseDocument, shipmentRouteSegment, locale);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorDataShipmentVoid", UtilMisc.toMap("errorString", e.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FileOutputStream(java.io.FileOutputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) File(java.io.File)

Example 4 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class UpsConnectException method upsEmailReturnLabel.

public static Map<String, Object> upsEmailReturnLabel(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator, shipmentId, locale);
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsGatewayNotAvailable", locale));
    }
    boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true"));
    String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context);
    File shipmentUpsSaveCertificationFile = null;
    if (shipmentUpsSaveCertificationInfo) {
        shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath);
        if (!shipmentUpsSaveCertificationFile.exists()) {
            shipmentUpsSaveCertificationFile.mkdirs();
        }
    }
    // Shipment Confirm request
    String shipmentConfirmResponseString = null;
    try {
        GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId).queryOne();
        if (shipment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "ProductShipmentNotFoundId", locale) + " " + shipmentId);
        }
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "ProductShipmentRouteSegmentNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale));
        }
        // Get Origin Info
        GenericValue originPostalAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originPostalAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentOriginPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        GenericValue originTelecomNumber = shipmentRouteSegment.getRelatedOne("OriginTelecomNumber", false);
        if (originTelecomNumber == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentOriginTelecomNumberNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        String originPhoneNumber = originTelecomNumber.getString("areaCode") + originTelecomNumber.getString("contactNumber");
        // don't put on country code if not specified or is the US country code (UPS wants it this way)
        if (UtilValidate.isNotEmpty(originTelecomNumber.getString("countryCode")) && !"001".equals(originTelecomNumber.getString("countryCode"))) {
            originPhoneNumber = originTelecomNumber.getString("countryCode") + originPhoneNumber;
        }
        originPhoneNumber = StringUtil.replaceString(originPhoneNumber, "-", "");
        originPhoneNumber = StringUtil.replaceString(originPhoneNumber, " ", "");
        // lookup the two letter country code (in the geoCode field)
        GenericValue originCountryGeo = originPostalAddress.getRelatedOne("CountryGeo", false);
        if (originCountryGeo == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentOriginCountryGeoNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        // Get Dest Info
        GenericValue destPostalAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destPostalAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentDestPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        GenericValue destTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false);
        if (destTelecomNumber == null) {
            String missingErrMsg = "DestTelecomNumber not found for ShipmentRouteSegment with shipmentId " + shipmentId + " and shipmentRouteSegmentId " + shipmentRouteSegmentId;
            Debug.logError(missingErrMsg, module);
        }
        String destPhoneNumber = null;
        if (destTelecomNumber != null) {
            destPhoneNumber = destTelecomNumber.getString("areaCode") + destTelecomNumber.getString("contactNumber");
            // don't put on country code if not specified or is the US country code (UPS wants it this way)
            if (UtilValidate.isNotEmpty(destTelecomNumber.getString("countryCode")) && !"001".equals(destTelecomNumber.getString("countryCode"))) {
                destPhoneNumber = destTelecomNumber.getString("countryCode") + destPhoneNumber;
            }
            destPhoneNumber = StringUtil.replaceString(destPhoneNumber, "-", "");
            destPhoneNumber = StringUtil.replaceString(destPhoneNumber, " ", "");
        }
        // lookup the two letter country code (in the geoCode field)
        GenericValue destCountryGeo = destPostalAddress.getRelatedOne("CountryGeo", false);
        if (destCountryGeo == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentDestCountryGeoNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("partyId", shipmentRouteSegment.get("carrierPartyId"), "roleTypeId", "CARRIER", "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")).queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentCarrierShipmentMethodNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "carrierPartyId", shipmentRouteSegment.get("carrierPartyId"), "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")), locale));
        }
        Map<String, Object> destEmail = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdTo"), "userLogin", userLogin));
        if (ServiceUtil.isError(destEmail)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(destEmail));
        }
        String recipientEmail = null;
        if (UtilValidate.isNotEmpty(destEmail.get("emailAddress"))) {
            recipientEmail = (String) destEmail.get("emailAddress");
        }
        String senderEmail = null;
        Map<String, Object> originEmail = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdFrom"), "userLogin", userLogin));
        if (ServiceUtil.isError(originEmail)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(originEmail));
        }
        if (UtilValidate.isNotEmpty(originEmail.get("emailAddress"))) {
            senderEmail = (String) originEmail.get("emailAddress");
        }
        List<GenericValue> shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        // Okay, start putting the XML together...
        Document shipmentConfirmRequestDoc = UtilXml.makeEmptyXmlDocument("ShipmentConfirmRequest");
        Element shipmentConfirmRequestElement = shipmentConfirmRequestDoc.getDocumentElement();
        shipmentConfirmRequestElement.setAttribute("xml:lang", "en-US");
        // Top Level Element: Request
        Element requestElement = UtilXml.addChildElement(shipmentConfirmRequestElement, "Request", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(requestElement, "RequestAction", "ShipConfirm", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(requestElement, "RequestOption", "nonvalidate", shipmentConfirmRequestDoc);
        // Top Level Element: Shipment
        Element shipmentElement = UtilXml.addChildElement(shipmentConfirmRequestElement, "Shipment", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipmentElement, "Description", "Goods for Shipment " + shipment.get("shipmentId"), shipmentConfirmRequestDoc);
        // Child of Shipment: ReturnService
        Element returnServiceElement = UtilXml.addChildElement(shipmentElement, "ReturnService", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(returnServiceElement, "Code", String.valueOf(returnServiceCode), shipmentConfirmRequestDoc);
        // Child of Shipment: Shipper
        String shipperNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperNumber", resource, "shipment.ups.shipper.number", "");
        Element shipperElement = UtilXml.addChildElement(shipmentElement, "Shipper", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperElement, "Name", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? originPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperElement, "PhoneNumber", originPhoneNumber, shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperElement, "ShipperNumber", shipperNumber, shipmentConfirmRequestDoc);
        Element shipperAddressElement = UtilXml.addChildElement(shipperElement, "Address", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperAddressElement, "AddressLine1", originPostalAddress.getString("address1"), shipmentConfirmRequestDoc);
        if (UtilValidate.isNotEmpty(originPostalAddress.getString("address2"))) {
            UtilXml.addChildElementValue(shipperAddressElement, "AddressLine2", originPostalAddress.getString("address2"), shipmentConfirmRequestDoc);
        }
        UtilXml.addChildElementValue(shipperAddressElement, "City", originPostalAddress.getString("city"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipperAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc);
        // Child of Shipment: ShipTo
        Element shipToElement = UtilXml.addChildElement(shipmentElement, "ShipTo", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? destPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? destPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc);
        if (UtilValidate.isNotEmpty(destPhoneNumber)) {
            UtilXml.addChildElementValue(shipToElement, "PhoneNumber", destPhoneNumber, shipmentConfirmRequestDoc);
        }
        Element shipToAddressElement = UtilXml.addChildElement(shipToElement, "Address", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipToAddressElement, "AddressLine1", destPostalAddress.getString("address1"), shipmentConfirmRequestDoc);
        if (UtilValidate.isNotEmpty(destPostalAddress.getString("address2"))) {
            UtilXml.addChildElementValue(shipToAddressElement, "AddressLine2", destPostalAddress.getString("address2"), shipmentConfirmRequestDoc);
        }
        UtilXml.addChildElementValue(shipToAddressElement, "City", destPostalAddress.getString("city"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipToAddressElement, "PostalCode", destPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipToAddressElement, "CountryCode", destCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc);
        if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("homeDeliveryType"))) {
            UtilXml.addChildElement(shipToAddressElement, "ResidentialAddress", shipmentConfirmRequestDoc);
        }
        // Child of Shipment: ShipFrom
        Element shipFromElement = UtilXml.addChildElement(shipmentElement, "ShipFrom", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipFromElement, "CompanyName", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? originPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipFromElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipFromElement, "PhoneNumber", originPhoneNumber, shipmentConfirmRequestDoc);
        Element shipFromAddressElement = UtilXml.addChildElement(shipFromElement, "Address", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine1", originPostalAddress.getString("address1"), shipmentConfirmRequestDoc);
        if (UtilValidate.isNotEmpty(originPostalAddress.getString("address2"))) {
            UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine2", originPostalAddress.getString("address2"), shipmentConfirmRequestDoc);
        }
        UtilXml.addChildElementValue(shipFromAddressElement, "City", originPostalAddress.getString("city"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipFromAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipFromAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(shipFromAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc);
        // Child of Shipment: PaymentInformation
        Element paymentInformationElement = UtilXml.addChildElement(shipmentElement, "PaymentInformation", shipmentConfirmRequestDoc);
        String thirdPartyAccountNumber = shipmentRouteSegment.getString("thirdPartyAccountNumber");
        if (UtilValidate.isEmpty(thirdPartyAccountNumber)) {
            // Paid by shipper
            Element prepaidElement = UtilXml.addChildElement(paymentInformationElement, "Prepaid", shipmentConfirmRequestDoc);
            Element billShipperElement = UtilXml.addChildElement(prepaidElement, "BillShipper", shipmentConfirmRequestDoc);
            // fill in BillShipper AccountNumber element from properties file
            String billShipperAccountNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "billShipperAccountNumber", resource, "shipment.ups.bill.shipper.account.number", "");
            UtilXml.addChildElementValue(billShipperElement, "AccountNumber", billShipperAccountNumber, shipmentConfirmRequestDoc);
        }
        // Child of Shipment: Service
        Element serviceElement = UtilXml.addChildElement(shipmentElement, "Service", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(serviceElement, "Code", carrierShipmentMethod.getString("carrierServiceCode"), shipmentConfirmRequestDoc);
        // Child of Shipment: ShipmentServiceOptions
        String defaultReturnLabelMemo = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "defaultReturnLabelMemo", resource, "shipment.ups.default.returnLabel.memo", "");
        String defaultReturnLabelSubject = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "defaultReturnLabelSubject", resource, "shipment.ups.default.returnLabel.subject", "");
        Element shipmentServiceOptionsElement = UtilXml.addChildElement(shipmentElement, "ShipmentServiceOptions", shipmentConfirmRequestDoc);
        Element labelDeliveryElement = UtilXml.addChildElement(shipmentServiceOptionsElement, "LabelDelivery", shipmentConfirmRequestDoc);
        Element emailMessageElement = UtilXml.addChildElement(labelDeliveryElement, "EMailMessage", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(emailMessageElement, "EMailAddress", recipientEmail, shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(emailMessageElement, "FromEMailAddress", senderEmail, shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(emailMessageElement, "FromName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(emailMessageElement, "Memo", defaultReturnLabelMemo, shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(emailMessageElement, "Subject", defaultReturnLabelSubject, shipmentConfirmRequestDoc);
        // Child of Shipment: Package
        Element packageElement = UtilXml.addChildElement(shipmentElement, "Package", shipmentConfirmRequestDoc);
        Element packagingTypeElement = UtilXml.addChildElement(packageElement, "PackagingType", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(packagingTypeElement, "Code", "02", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(packageElement, "Description", "Package Description", shipmentConfirmRequestDoc);
        Element packageWeightElement = UtilXml.addChildElement(packageElement, "PackageWeight", shipmentConfirmRequestDoc);
        Element packageWeightUnitOfMeasurementElement = UtilXml.addChildElement(packageElement, "UnitOfMeasurement", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(packageWeightUnitOfMeasurementElement, "Code", "LBS", shipmentConfirmRequestDoc);
        UtilXml.addChildElementValue(packageWeightElement, "Weight", EntityUtilProperties.getPropertyValue("shipment", "shipment.default.weight.value", delegator), shipmentConfirmRequestDoc);
        String shipmentConfirmRequestString = null;
        try {
            shipmentConfirmRequestString = UtilXml.writeXmlDocument(shipmentConfirmRequestDoc);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the ShipmentConfirmRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorShipmentConfirmRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // create AccessRequest XML doc
        Document accessRequestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, resource);
        String accessRequestString = null;
        try {
            accessRequestString = UtilXml.writeXmlDocument(accessRequestDocument);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the AccessRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorAccessRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // connect to UPS server, send AccessRequest to auth
        // send ShipmentConfirmRequest String
        // get ShipmentConfirmResponse String back
        StringBuilder xmlString = new StringBuilder();
        xmlString.append(accessRequestString);
        xmlString.append(shipmentConfirmRequestString);
        try {
            shipmentConfirmResponseString = sendUpsRequest("ShipConfirm", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale);
        } catch (UpsConnectException e) {
            String uceErrMsg = "Error sending UPS request for UPS Service ShipConfirm: " + e.toString();
            Debug.logError(e, uceErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorSendingShipConfirm", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        Document shipmentConfirmResponseDocument = null;
        try {
            shipmentConfirmResponseDocument = UtilXml.readXmlDocument(shipmentConfirmResponseString, false);
        } catch (SAXException e2) {
            String excErrMsg = "Error parsing the ShipmentConfirmResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingShipmentConfirm", UtilMisc.toMap("errorString", e2.toString()), locale));
        } catch (ParserConfigurationException e2) {
            String excErrMsg = "Error parsing the ShipmentConfirmResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingShipmentConfirm", UtilMisc.toMap("errorString", e2.toString()), locale));
        } catch (IOException e2) {
            String excErrMsg = "Error parsing the ShipmentConfirmResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingShipmentConfirm", UtilMisc.toMap("errorString", e2.toString()), locale));
        }
        Element shipmentConfirmResponseElement = shipmentConfirmResponseDocument.getDocumentElement();
        // handle Response element info
        Element responseElement = UtilXml.firstChildElement(shipmentConfirmResponseElement, "Response");
        String responseStatusCode = UtilXml.childElementValue(responseElement, "ResponseStatusCode");
        List<Object> errorList = new LinkedList<Object>();
        UpsServices.handleErrors(responseElement, errorList, locale);
        if (!"1".equals(responseStatusCode)) {
            errorList.add(0, UtilProperties.getMessage(resourceError, "FacilityShipmentUpsShipmentConfirmFailedForReturnShippingLabel", locale));
            return ServiceUtil.returnError(errorList);
        }
        // Shipment Accept Request follows
        if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale));
        }
        if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        String shipmentDigest = UtilXml.childElementValue(shipmentConfirmResponseElement, "ShipmentDigest");
        if (UtilValidate.isEmpty(shipmentDigest)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsTrackingDigestWasNotSet", locale));
        }
        Document shipmentAcceptRequestDoc = UtilXml.makeEmptyXmlDocument("ShipmentAcceptRequest");
        Element shipmentAcceptRequestElement = shipmentAcceptRequestDoc.getDocumentElement();
        shipmentAcceptRequestElement.setAttribute("xml:lang", "en-US");
        // Top Level Element: Request
        Element acceptRequestElement = UtilXml.addChildElement(shipmentAcceptRequestElement, "Request", shipmentAcceptRequestDoc);
        Element acceptTransactionReferenceElement = UtilXml.addChildElement(acceptRequestElement, "TransactionReference", shipmentAcceptRequestDoc);
        UtilXml.addChildElementValue(acceptTransactionReferenceElement, "CustomerContext", "ShipAccept / 01", shipmentAcceptRequestDoc);
        UtilXml.addChildElementValue(acceptTransactionReferenceElement, "XpciVersion", "1.0001", shipmentAcceptRequestDoc);
        UtilXml.addChildElementValue(acceptRequestElement, "RequestAction", "ShipAccept", shipmentAcceptRequestDoc);
        UtilXml.addChildElementValue(acceptRequestElement, "RequestOption", "01", shipmentAcceptRequestDoc);
        UtilXml.addChildElementValue(shipmentAcceptRequestElement, "ShipmentDigest", shipmentDigest, shipmentAcceptRequestDoc);
        String shipmentAcceptRequestString = null;
        try {
            shipmentAcceptRequestString = UtilXml.writeXmlDocument(shipmentAcceptRequestDoc);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the ShipmentAcceptRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorShipmentAcceptRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // create AccessRequest XML doc
        Document acceptAccessRequestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, resource);
        String acceptAccessRequestString = null;
        try {
            acceptAccessRequestString = UtilXml.writeXmlDocument(acceptAccessRequestDocument);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the AccessRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorAccessRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // connect to UPS server, send AccessRequest to auth
        StringBuilder acceptXmlString = new StringBuilder();
        acceptXmlString.append(acceptAccessRequestString);
        acceptXmlString.append(shipmentAcceptRequestString);
        if (shipmentUpsSaveCertificationInfo) {
            String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentAcceptRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml";
            try (FileOutputStream fileOut = new FileOutputStream(outFileName)) {
                fileOut.write(xmlString.toString().getBytes(UtilIO.getUtf8()));
                fileOut.flush();
            } catch (IOException e) {
                Debug.logInfo(e, "Could not save UPS XML file: [[[" + xmlString.toString() + "]]] to file: " + outFileName, module);
            }
        }
        try {
            sendUpsRequest("ShipAccept", acceptXmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale);
        } catch (UpsConnectException e) {
            String uceErrMsg = "Error sending UPS request for UPS Service ShipAccept: " + e.toString();
            Debug.logError(e, uceErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorSendingShipAccept", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorDataShipmentAccept", UtilMisc.toMap("errorString", e.toString()), locale));
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorDataShipmentConfirm", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    return ServiceUtil.returnSuccess(UtilProperties.getMessage("OrderUiLabels", "OrderReturnLabelEmailSuccessful", locale));
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) LinkedList(java.util.LinkedList) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FileOutputStream(java.io.FileOutputStream) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) File(java.io.File)

Example 5 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class UpsConnectException method upsTrackShipment.

public static Map<String, Object> upsTrackShipment(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator, shipmentId, locale);
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsGatewayNotAvailable", locale));
    }
    boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true"));
    String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context);
    File shipmentUpsSaveCertificationFile = null;
    if (shipmentUpsSaveCertificationInfo) {
        shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath);
        if (!shipmentUpsSaveCertificationFile.exists()) {
            shipmentUpsSaveCertificationFile.mkdirs();
        }
    }
    String trackResponseString = null;
    try {
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale));
        }
        // add ShipmentRouteSegment carrierServiceStatusId, check before all UPS services
        if (!"SHRSCS_ACCEPTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRouteSegmentStatusNotAccepted", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale));
        }
        List<GenericValue> shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        if (UtilValidate.isEmpty(shipmentRouteSegment.getString("trackingIdNumber"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsTrackingIdNumberWasNotSet", locale));
        }
        Document trackRequestDoc = UtilXml.makeEmptyXmlDocument("TrackRequest");
        Element trackRequestElement = trackRequestDoc.getDocumentElement();
        trackRequestElement.setAttribute("xml:lang", "en-US");
        // Top Level Element: Request
        Element requestElement = UtilXml.addChildElement(trackRequestElement, "Request", trackRequestDoc);
        Element transactionReferenceElement = UtilXml.addChildElement(requestElement, "TransactionReference", trackRequestDoc);
        UtilXml.addChildElementValue(transactionReferenceElement, "CustomerContext", "Track", trackRequestDoc);
        UtilXml.addChildElementValue(transactionReferenceElement, "XpciVersion", "1.0001", trackRequestDoc);
        UtilXml.addChildElementValue(requestElement, "RequestAction", "Track", trackRequestDoc);
        UtilXml.addChildElementValue(trackRequestElement, "ShipmentIdentificationNumber", shipmentRouteSegment.getString("trackingIdNumber"), trackRequestDoc);
        String trackRequestString = null;
        try {
            trackRequestString = UtilXml.writeXmlDocument(trackRequestDoc);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the TrackRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorTrackRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // create AccessRequest XML doc
        Document accessRequestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, resource);
        String accessRequestString = null;
        try {
            accessRequestString = UtilXml.writeXmlDocument(accessRequestDocument);
        } catch (IOException e) {
            String ioeErrMsg = "Error writing the AccessRequest XML Document to a String: " + e.toString();
            Debug.logError(e, ioeErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorAccessRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // connect to UPS server, send AccessRequest to auth
        // send ShipmentConfirmRequest String
        // get ShipmentConfirmResponse String back
        StringBuilder xmlString = new StringBuilder();
        xmlString.append(accessRequestString);
        xmlString.append(trackRequestString);
        if (shipmentUpsSaveCertificationInfo) {
            String outFileName = shipmentUpsSaveCertificationPath + "/UpsTrackRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml";
            try (FileOutputStream fileOut = new FileOutputStream(outFileName)) {
                fileOut.write(xmlString.toString().getBytes(UtilIO.getUtf8()));
                fileOut.flush();
            } catch (IOException e) {
                Debug.logInfo(e, "Could not save UPS XML file: [[[" + xmlString.toString() + "]]] to file: " + outFileName, module);
            }
        }
        try {
            trackResponseString = sendUpsRequest("Track", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale);
        } catch (UpsConnectException e) {
            String uceErrMsg = "Error sending UPS request for UPS Service Track: " + e.toString();
            Debug.logError(e, uceErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorSendingTrack", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        if (shipmentUpsSaveCertificationInfo) {
            String outFileName = shipmentUpsSaveCertificationPath + "/UpsTrackResponseString" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml";
            try (FileOutputStream fileOut = new FileOutputStream(outFileName)) {
                fileOut.write(trackResponseString.getBytes(UtilIO.getUtf8()));
                fileOut.flush();
            } catch (IOException e) {
                Debug.logInfo(e, "Could not save UPS XML file: [[[" + xmlString.toString() + "]]] to file: " + outFileName, module);
            }
        }
        Document trackResponseDocument = null;
        try {
            trackResponseDocument = UtilXml.readXmlDocument(trackResponseString, false);
        } catch (SAXException e2) {
            String excErrMsg = "Error parsing the TrackResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingTrackResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
        } catch (ParserConfigurationException e2) {
            String excErrMsg = "Error parsing the TrackResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingTrackResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
        } catch (IOException e2) {
            String excErrMsg = "Error parsing the TrackResponse: " + e2.toString();
            Debug.logError(e2, excErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingTrackResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
        }
        return handleUpsTrackShipmentResponse(trackResponseDocument, shipmentRouteSegment, shipmentPackageRouteSegs, locale);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorDataShipmentTrack", UtilMisc.toMap("errorString", e.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FileOutputStream(java.io.FileOutputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) File(java.io.File)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)1422 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)871 Delegator (org.apache.ofbiz.entity.Delegator)721 Locale (java.util.Locale)505 HashMap (java.util.HashMap)463 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)370 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)356 BigDecimal (java.math.BigDecimal)338 LinkedList (java.util.LinkedList)312 Timestamp (java.sql.Timestamp)202 GeneralException (org.apache.ofbiz.base.util.GeneralException)168 Map (java.util.Map)155 IOException (java.io.IOException)116 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)97 HttpSession (javax.servlet.http.HttpSession)89 ArrayList (java.util.ArrayList)69 Security (org.apache.ofbiz.security.Security)69 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)59 List (java.util.List)56 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)52