Search in sources :

Example 21 with Delegator

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

the class ShipmentServices method removeShipmentEstimate.

public static Map<String, Object> removeShipmentEstimate(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentCostEstimateId = (String) context.get("shipmentCostEstimateId");
    Locale locale = (Locale) context.get("locale");
    GenericValue estimate = null;
    try {
        estimate = EntityQuery.use(delegator).from("ShipmentCostEstimate").where("shipmentCostEstimateId", shipmentCostEstimateId).queryOne();
        estimate.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductShipmentCostEstimateRemoveError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 22 with Delegator

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

the class ShipmentServices method updatePurchaseShipmentFromReceipt.

/**
 * Whenever a ShipmentReceipt is generated, check the Shipment associated
 * with it to see if all items were received. If so, change its status to
 * PURCH_SHIP_RECEIVED. The check is accomplished by counting the
 * products shipped (from ShipmentAndItem) and matching them with the
 * products received (from ShipmentReceipt).
 */
public static Map<String, Object> updatePurchaseShipmentFromReceipt(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentId = (String) context.get("shipmentId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    try {
        List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).from("ShipmentReceipt").where("shipmentId", shipmentId).queryList();
        if (shipmentReceipts.size() == 0)
            return ServiceUtil.returnSuccess();
        // If there are shipment receipts, the shipment must have been shipped, so set the shipment status to PURCH_SHIP_SHIPPED if it's only PURCH_SHIP_CREATED
        GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId).queryOne();
        if ((!UtilValidate.isEmpty(shipment)) && "PURCH_SHIP_CREATED".equals(shipment.getString("statusId"))) {
            Map<String, Object> updateShipmentMap = dispatcher.runSync("updateShipment", UtilMisc.<String, Object>toMap("shipmentId", shipmentId, "statusId", "PURCH_SHIP_SHIPPED", "userLogin", userLogin));
            if (ServiceUtil.isError(updateShipmentMap)) {
                return updateShipmentMap;
            }
        }
        List<GenericValue> shipmentAndItems = EntityQuery.use(delegator).from("ShipmentAndItem").where("shipmentId", shipmentId, "statusId", "PURCH_SHIP_SHIPPED").queryList();
        if (shipmentAndItems.size() == 0) {
            return ServiceUtil.returnSuccess();
        }
        // store the quantity of each product shipped in a hashmap keyed to productId
        Map<String, BigDecimal> shippedCountMap = new HashMap<String, BigDecimal>();
        for (GenericValue item : shipmentAndItems) {
            BigDecimal shippedQuantity = item.getBigDecimal("quantity");
            BigDecimal quantity = shippedCountMap.get(item.getString("productId"));
            quantity = quantity == null ? shippedQuantity : shippedQuantity.add(quantity);
            shippedCountMap.put(item.getString("productId"), quantity);
        }
        // store the quantity of each product received in a hashmap keyed to productId
        Map<String, BigDecimal> receivedCountMap = new HashMap<String, BigDecimal>();
        for (GenericValue item : shipmentReceipts) {
            BigDecimal receivedQuantity = item.getBigDecimal("quantityAccepted");
            BigDecimal quantity = receivedCountMap.get(item.getString("productId"));
            quantity = quantity == null ? receivedQuantity : receivedQuantity.add(quantity);
            receivedCountMap.put(item.getString("productId"), quantity);
        }
        // let Map.equals do all the hard comparison work
        if (!shippedCountMap.equals(receivedCountMap)) {
            return ServiceUtil.returnSuccess();
        }
        // now update the shipment
        Map<String, Object> serviceResult = dispatcher.runSync("updateShipment", UtilMisc.<String, Object>toMap("shipmentId", shipmentId, "statusId", "PURCH_SHIP_RECEIVED", "userLogin", userLogin));
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    } catch (GenericServiceException se) {
        Debug.logError(se, module);
        return ServiceUtil.returnError(se.getMessage());
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal)

Example 23 with Delegator

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

the class PackingSessionLine method issueItemToShipment.

protected void issueItemToShipment(String shipmentId, String picklistBinId, GenericValue userLogin, BigDecimal quantity, LocalDispatcher dispatcher) throws GeneralException {
    if (quantity == null) {
        quantity = this.getQuantity();
    }
    Map<String, Object> issueMap = new HashMap<String, Object>();
    issueMap.put("shipmentId", shipmentId);
    issueMap.put("orderId", this.getOrderId());
    issueMap.put("orderItemSeqId", this.getOrderItemSeqId());
    issueMap.put("shipGroupSeqId", this.getShipGroupSeqId());
    issueMap.put("inventoryItemId", this.getInventoryItemId());
    issueMap.put("quantity", quantity);
    issueMap.put("userLogin", userLogin);
    Map<String, Object> issueResp = dispatcher.runSync("issueOrderItemShipGrpInvResToShipment", issueMap);
    if (ServiceUtil.isError(issueResp)) {
        throw new GeneralException(ServiceUtil.getErrorMessage(issueResp));
    }
    String shipmentItemSeqId = (String) issueResp.get("shipmentItemSeqId");
    if (shipmentItemSeqId == null) {
        throw new GeneralException("Issue item did not return a valid shipmentItemSeqId!");
    } else {
        this.setShipmentItemSeqId(shipmentItemSeqId);
    }
    if (picklistBinId != null) {
        // find the pick list item
        Debug.logInfo("Looking up picklist item for bin ID #" + picklistBinId, module);
        Delegator delegator = dispatcher.getDelegator();
        Map<String, Object> itemLookup = new HashMap<String, Object>();
        itemLookup.put("picklistBinId", picklistBinId);
        itemLookup.put("orderId", this.getOrderId());
        itemLookup.put("orderItemSeqId", this.getOrderItemSeqId());
        itemLookup.put("shipGroupSeqId", this.getShipGroupSeqId());
        itemLookup.put("inventoryItemId", this.getInventoryItemId());
        GenericValue plItem = EntityQuery.use(delegator).from("PicklistItem").where(itemLookup).queryOne();
        if (plItem != null) {
            Debug.logInfo("Found picklist bin: " + plItem, module);
            BigDecimal itemQty = plItem.getBigDecimal("quantity");
            if (itemQty.compareTo(quantity) == 0) {
                // set to complete
                itemLookup.put("itemStatusId", "PICKITEM_COMPLETED");
            } else {
                itemLookup.put("itemStatusId", "PICKITEM_CANCELLED");
            }
            itemLookup.put("userLogin", userLogin);
            Map<String, Object> itemUpdateResp = dispatcher.runSync("updatePicklistItem", itemLookup);
            if (ServiceUtil.isError(itemUpdateResp)) {
                throw new GeneralException(ServiceUtil.getErrorMessage(issueResp));
            }
        } else {
            Debug.logInfo("No item was found for lookup: " + itemLookup, module);
        }
    } else {
        Debug.logWarning("*** NO Picklist Bin ID set; cannot update picklist status!", module);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) BigDecimal(java.math.BigDecimal)

Example 24 with Delegator

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

the class ShipmentEvents method viewShipmentPackageRouteSegLabelImage.

public static String viewShipmentPackageRouteSegLabelImage(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String shipmentId = request.getParameter("shipmentId");
    String shipmentRouteSegmentId = request.getParameter("shipmentRouteSegmentId");
    String shipmentPackageSeqId = request.getParameter("shipmentPackageSeqId");
    GenericValue shipmentPackageRouteSeg = null;
    try {
        shipmentPackageRouteSeg = EntityQuery.use(delegator).from("ShipmentPackageRouteSeg").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentPackageSeqId", shipmentPackageSeqId).queryOne();
    } catch (GenericEntityException e) {
        String errorMsg = "Error looking up ShipmentPackageRouteSeg: " + e.toString();
        Debug.logError(e, errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }
    if (shipmentPackageRouteSeg == null) {
        request.setAttribute("_ERROR_MESSAGE_", "Could not find ShipmentPackageRouteSeg where shipmentId=[" + shipmentId + "], shipmentRouteSegmentId=[" + shipmentRouteSegmentId + "], shipmentPackageSeqId=[" + shipmentPackageSeqId + "]");
        return "error";
    }
    byte[] bytes = shipmentPackageRouteSeg.getBytes("labelImage");
    if (bytes == null || bytes.length == 0) {
        request.setAttribute("_ERROR_MESSAGE_", "The ShipmentPackageRouteSeg was found where shipmentId=[" + shipmentId + "], shipmentRouteSegmentId=[" + shipmentRouteSegmentId + "], shipmentPackageSeqId=[" + shipmentPackageSeqId + "], but there was no labelImage on the value.");
        return "error";
    }
    // It would be nice to store the actual type of the image alongside the image data.
    try {
        UtilHttp.streamContentToBrowser(response, bytes, "image/gif");
    } catch (IOException e1) {
        try {
            UtilHttp.streamContentToBrowser(response, bytes, "image/png");
        } catch (IOException e2) {
            String errorMsg = "Error writing labelImage to OutputStream: " + e2.toString();
            Debug.logError(e2, errorMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errorMsg);
            return "error";
        }
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) IOException(java.io.IOException)

Example 25 with Delegator

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

the class DhlConnectException method dhlShipmentConfirm.

/*
     * Pass a shipment request to DHL via ShipIT and get a tracking number and a label back, among other things
     */
public static Map<String, Object> dhlShipmentConfirm(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    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, "FacilityShipmentDhlGatewayNotAvailable", locale));
    }
    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 (!"DHL".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale));
        }
        // add ShipmentRouteSegment carrierServiceStatusId, check before all DHL services
        if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("carrierServiceStatusId")) && !"SHRSCS_NOT_STARTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlRouteSegmentStatusNotStarted", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale));
        }
        // Get Origin Info
        GenericValue originPostalAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originPostalAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentOriginPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        GenericValue originTelecomNumber = shipmentRouteSegment.getRelatedOne("OriginTelecomNumber", false);
        if (originTelecomNumber == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentOriginTelecomNumberNotFound", 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 and assuming DHL will accept this)
        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, "FacilityShipmentRouteSegmentOriginCountryGeoNotFound", 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, "FacilityShipmentRouteSegmentDestPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        // DHL requires destination phone number, default to sender # if no customer number
        String destPhoneNumber = originPhoneNumber;
        GenericValue destTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false);
        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, " ", "");
        }
        String recipientEmail = null;
        Map<String, Object> results = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdTo"), "userLogin", userLogin));
        if (ServiceUtil.isError(results)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results));
        }
        if (results.get("emailAddress") != null) {
            recipientEmail = (String) results.get("emailAddress");
        }
        // 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, "FacilityShipmentRouteSegmentDestCountryGeoNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        List<GenericValue> shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        if (shipmentPackageRouteSegs.size() != 1) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlMultiplePackagesNotSupported", locale));
        }
        // get the weight from the ShipmentRouteSegment first, which overrides all later weight computations
        // for later overrides
        boolean hasBillingWeight = false;
        BigDecimal billingWeight = shipmentRouteSegment.getBigDecimal("billingWeight");
        String billingWeightUomId = shipmentRouteSegment.getString("billingWeightUomId");
        if ((billingWeight != null) && (billingWeight.compareTo(BigDecimal.ZERO) > 0)) {
            hasBillingWeight = true;
            if (billingWeightUomId == null) {
                Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId, module);
                // TODO: this should be specified in a properties file
                billingWeightUomId = "WT_lb";
            }
            // convert
            results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", billingWeightUomId, "uomIdTo", DHL_WEIGHT_UOM_ID, "originalValue", billingWeight));
            if (ServiceUtil.isError(results) || (results.get("convertedValue") == null)) {
                Debug.logWarning("Unable to convert billing weights for shipmentId " + shipmentId, module);
                // try getting the weight from package instead
                hasBillingWeight = false;
            } else {
                billingWeight = (BigDecimal) results.get("convertedValue");
            }
        }
        // loop through Shipment segments (NOTE: only one supported, loop is here for future refactoring reference)
        BigDecimal packageWeight = null;
        for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegs) {
            GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);
            GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false);
            if (shipmentBoxType != null) {
            // TODO: determine what default UoM is (assuming inches) - there should be a defaultDimensionUomId in Facility
            }
            // next step is weight determination, so skip if we have a billing weight
            if (hasBillingWeight)
                continue;
            // compute total packageWeight (for now, just one package)
            if (shipmentPackage.getString("weight") != null) {
                packageWeight = new BigDecimal(shipmentPackage.getString("weight"));
            } else {
                // use default weight if available
                try {
                    packageWeight = EntityUtilProperties.getPropertyAsBigDecimal(shipmentPropertiesFile, "shipment.default.weight.value", BigDecimal.ZERO);
                } catch (NumberFormatException ne) {
                    Debug.logWarning("Default shippable weight not configured (shipment.default.weight.value)", module);
                    packageWeight = BigDecimal.ONE;
                }
            }
            // convert weight
            String weightUomId = (String) shipmentPackage.get("weightUomId");
            if (weightUomId == null) {
                Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId, module);
                // TODO: this should be specified in a properties file
                weightUomId = "WT_lb";
            }
            results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", weightUomId, "uomIdTo", DHL_WEIGHT_UOM_ID, "originalValue", packageWeight));
            if (ServiceUtil.isError(results)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results));
            }
            if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) || (results.get("convertedValue") == null)) {
                Debug.logWarning("Unable to convert weights for shipmentId " + shipmentId, module);
                packageWeight = BigDecimal.ONE;
            } else {
                packageWeight = (BigDecimal) results.get("convertedValue");
            }
        }
        // pick which weight to use and round it
        BigDecimal weight = null;
        if (hasBillingWeight) {
            weight = billingWeight;
        } else {
            weight = packageWeight;
        }
        // want the rounded weight as a string, so we use the "" + int shortcut
        String roundedWeight = weight.setScale(0, RoundingMode.HALF_UP).toPlainString();
        // translate shipmentMethodTypeId to DHL service code
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String dhlShipmentDetailCode = null;
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("shipmentMethodTypeId", shipmentMethodTypeId, "partyId", "DHL", "roleTypeId", "CARRIER").queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlNoCarrierShipmentMethod", UtilMisc.toMap("carrierPartyId", "DHL", "shipmentMethodTypeId", shipmentMethodTypeId), locale));
        }
        dhlShipmentDetailCode = carrierShipmentMethod.getString("carrierServiceCode");
        // 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));
        }
        // label image preference (PNG or GIF)
        String labelImagePreference = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "labelImageFormat", resource, "shipment.dhl.label.image.format");
        if (labelImagePreference.isEmpty()) {
            Debug.logInfo("shipment.dhl.label.image.format not specified, assuming PNG", module);
            labelImagePreference = "PNG";
        } else if (!("PNG".equals(labelImagePreference) || "GIF".equals(labelImagePreference))) {
            Debug.logError("Illegal shipment.dhl.label.image.format: " + labelImagePreference, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlUnknownLabelImageFormat", UtilMisc.toMap("labelImagePreference", labelImagePreference), locale));
        }
        // 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, "FacilityShipmentDhlRateEstimateTemplateNotConfigured", locale));
        }
        StringWriter outWriter = new StringWriter();
        Map<String, Object> inContext = new HashMap<String, Object>();
        inContext.put("action", "GenerateLabel");
        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", roundedWeight);
        inContext.put("senderPhoneNbr", originPhoneNumber);
        inContext.put("companyName", destPostalAddress.getString("toName"));
        inContext.put("attnTo", destPostalAddress.getString("attnName"));
        inContext.put("street", destPostalAddress.getString("address1"));
        inContext.put("streetLine2", destPostalAddress.getString("address2"));
        inContext.put("city", destPostalAddress.getString("city"));
        inContext.put("state", destPostalAddress.getString("stateProvinceGeoId"));
        // DHL ShipIT API does not accept ZIP+4
        if ((destPostalAddress.getString("postalCode") != null) && (destPostalAddress.getString("postalCode").length() > 5)) {
            inContext.put("postalCode", destPostalAddress.getString("postalCode").substring(0, 5));
        } else {
            inContext.put("postalCode", destPostalAddress.getString("postalCode"));
        }
        inContext.put("phoneNbr", destPhoneNumber);
        inContext.put("labelImageType", labelImagePreference);
        inContext.put("shipperReference", shipment.getString("primaryOrderId") + "-" + shipment.getString("primaryShipGroupSeqId"));
        inContext.put("notifyEmailAddress", recipientEmail);
        try {
            ContentWorker.renderContentAsText(dispatcher, templateName, outWriter, inContext, locale, "text/plain", null, null, false);
        } catch (Exception e) {
            Debug.logError(e, "Cannot confirm DHL shipment: Failed to render DHL XML Request.", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexRateTemplateRenderingError", locale));
        }
        String requestString = outWriter.toString();
        if (Debug.verboseOn()) {
            Debug.logVerbose(requestString, module);
        }
        // send the request
        String responseString = null;
        try {
            responseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, resource, locale);
            if (Debug.verboseOn()) {
                Debug.logVerbose(responseString, 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, "FacilityShipmentFedexRateTemplateSendingError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // pass to handler method
        return handleDhlShipmentConfirmResponse(responseString, shipmentRouteSegment, shipmentPackageRouteSegs, locale);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexRateTemplateReadingError", UtilMisc.toMap("errorString", e.toString()), locale));
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexRateTemplateReadingError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) 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) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

Delegator (org.apache.ofbiz.entity.Delegator)869 GenericValue (org.apache.ofbiz.entity.GenericValue)721 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)611 Locale (java.util.Locale)485 HashMap (java.util.HashMap)328 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)278 BigDecimal (java.math.BigDecimal)205 LinkedList (java.util.LinkedList)166 Timestamp (java.sql.Timestamp)163 GeneralException (org.apache.ofbiz.base.util.GeneralException)130 IOException (java.io.IOException)117 Map (java.util.Map)113 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)61 Security (org.apache.ofbiz.security.Security)60 HttpSession (javax.servlet.http.HttpSession)59 Properties (java.util.Properties)37 UtilProperties (org.apache.ofbiz.base.util.UtilProperties)37 EntityUtilProperties (org.apache.ofbiz.entity.util.EntityUtilProperties)35 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)33