Search in sources :

Example 26 with GenericValue

use of org.apache.ofbiz.entity.GenericValue 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 27 with GenericValue

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

the class ShipmentWorker method getShipmentPackageContentValue.

/*
     * Returns the value of a given ShipmentPackageContent record.  Calculated by working out the total value (from the OrderItems) of all ItemIssuances
     * for the ShipmentItem then dividing that by the total quantity issued for the same to get an average item value then multiplying that by the package
     * content quantity.
     * Note: No rounding of the calculation is performed so you will need to round it to the accuracy that you require
     */
public static BigDecimal getShipmentPackageContentValue(GenericValue shipmentPackageContent) {
    BigDecimal quantity = shipmentPackageContent.getBigDecimal("quantity");
    BigDecimal value;
    // lookup the issuance to find the order
    List<GenericValue> issuances = null;
    try {
        GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem", false);
        issuances = shipmentItem.getRelated("ItemIssuance", null, null, false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    BigDecimal totalIssued = BigDecimal.ZERO;
    BigDecimal totalValue = BigDecimal.ZERO;
    if (UtilValidate.isNotEmpty(issuances)) {
        for (GenericValue issuance : issuances) {
            // we only need one
            BigDecimal issuanceQuantity = issuance.getBigDecimal("quantity");
            BigDecimal issuanceCancelQuantity = issuance.getBigDecimal("cancelQuantity");
            if (issuanceCancelQuantity != null) {
                issuanceQuantity = issuanceQuantity.subtract(issuanceCancelQuantity);
            }
            // get the order item
            GenericValue orderItem = null;
            try {
                orderItem = issuance.getRelatedOne("OrderItem", false);
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (orderItem != null) {
                // get the value per unit - (base price * amount)
                BigDecimal selectedAmount = orderItem.getBigDecimal("selectedAmount");
                if (selectedAmount == null || selectedAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    selectedAmount = BigDecimal.ONE;
                }
                BigDecimal unitPrice = orderItem.getBigDecimal("unitPrice");
                BigDecimal itemValue = unitPrice.multiply(selectedAmount);
                // total value for package (per unit * quantity)
                totalIssued = totalIssued.add(issuanceQuantity);
                totalValue = totalValue.add(itemValue.multiply(issuanceQuantity));
            }
        }
    }
    // take the average value of the issuances and multiply it by the shipment package content quantity
    value = totalValue.divide(totalIssued, 10, RoundingMode.HALF_EVEN).multiply(quantity);
    return value;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BigDecimal(java.math.BigDecimal)

Example 28 with GenericValue

use of org.apache.ofbiz.entity.GenericValue 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)

Example 29 with GenericValue

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

the class DhlConnectException method handleDhlShipmentConfirmResponse.

// NOTE: Must VOID shipments on errors
public static Map<String, Object> handleDhlShipmentConfirmResponse(String rateResponseString, GenericValue shipmentRouteSegment, List<GenericValue> shipmentPackageRouteSegs, Locale locale) throws GenericEntityException {
    GenericValue shipmentPackageRouteSeg = shipmentPackageRouteSegs.get(0);
    // TODO: figure out how to handle validation on return XML, which can be mangled
    // Ideas: try again right away, let user try again, etc.
    Document rateResponseDocument = null;
    try {
        rateResponseDocument = UtilXml.readXmlDocument(rateResponseString, false);
    } catch (SAXException e2) {
        String excErrMsg = "Error parsing the RatingServiceSelectionResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
    // TODO: VOID
    } catch (ParserConfigurationException e2) {
        String excErrMsg = "Error parsing the RatingServiceSelectionResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
    // TODO VOID
    } catch (IOException e2) {
        String excErrMsg = "Error parsing the RatingServiceSelectionResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
    // TODO VOID
    }
    // tracking number: Shipment/ShipmentDetail/AirbillNbr
    Element rootElement = rateResponseDocument.getDocumentElement();
    Element shipmentElement = UtilXml.firstChildElement(rootElement, "Shipment");
    Element shipmentDetailElement = UtilXml.firstChildElement(shipmentElement, "ShipmentDetail");
    String trackingNumber = UtilXml.childElementValue(shipmentDetailElement, "AirbillNbr");
    // label: Shipment/Label/Image
    Element labelElement = UtilXml.firstChildElement(shipmentElement, "Label");
    String encodedImageString = UtilXml.childElementValue(labelElement, "Image");
    if (encodedImageString == null) {
        Debug.logError("Cannot find response DHL shipment label.  Rate response document is: " + rateResponseString, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlShipmentLabelError", UtilMisc.toMap("shipmentPackageRouteSeg", shipmentPackageRouteSeg, "rateResponseString", rateResponseString), locale));
    }
    // TODO: this is a temporary hack to replace the newlines so that Base64 likes the input This is NOT platform independent
    int size = encodedImageString.length();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < size; i++) {
        if (encodedImageString.charAt(i) == '\n')
            continue;
        sb.append(encodedImageString.charAt(i));
    }
    byte[] labelBytes = Base64.base64Decode(sb.toString().getBytes(UtilIO.getUtf8()));
    if (labelBytes != null) {
        // store in db blob
        shipmentPackageRouteSeg.setBytes("labelImage", labelBytes);
    } else {
        Debug.logInfo("Failed to either decode returned DHL label or no data found in eCommerce/Shipment/Label/Image.", module);
    // TODO: VOID
    }
    shipmentPackageRouteSeg.set("trackingCode", trackingNumber);
    shipmentPackageRouteSeg.set("labelHtml", sb.toString());
    shipmentPackageRouteSeg.store();
    shipmentRouteSegment.set("trackingIdNumber", trackingNumber);
    shipmentRouteSegment.put("carrierServiceStatusId", "SHRSCS_CONFIRMED");
    shipmentRouteSegment.store();
    return ServiceUtil.returnSuccess(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlShipmentConfirmed", locale));
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Element(org.w3c.dom.Element) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException)

Example 30 with GenericValue

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

the class InventoryServices method completeInventoryTransfer.

public static Map<String, Object> completeInventoryTransfer(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String inventoryTransferId = (String) context.get("inventoryTransferId");
    Timestamp receiveDate = (Timestamp) context.get("receiveDate");
    GenericValue inventoryTransfer = null;
    GenericValue inventoryItem = null;
    GenericValue destinationFacility = null;
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    try {
        inventoryTransfer = EntityQuery.use(delegator).from("InventoryTransfer").where("inventoryTransferId", inventoryTransferId).queryOne();
        inventoryItem = inventoryTransfer.getRelatedOne("InventoryItem", false);
        destinationFacility = inventoryTransfer.getRelatedOne("ToFacility", false);
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemLookupProblem", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }
    if (inventoryItem == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemLookupProblem", UtilMisc.toMap("errorString", ""), locale));
    }
    String inventoryType = inventoryItem.getString("inventoryItemTypeId");
    // set the fields on the transfer record
    if (inventoryTransfer.get("receiveDate") == null) {
        if (receiveDate != null) {
            inventoryTransfer.set("receiveDate", receiveDate);
        } else {
            inventoryTransfer.set("receiveDate", UtilDateTime.nowTimestamp());
        }
    }
    if ("NON_SERIAL_INV_ITEM".equals(inventoryType)) {
        // add an adjusting InventoryItemDetail so set ATP back to QOH: ATP = ATP + (QOH - ATP), diff = QOH - ATP
        BigDecimal atp = inventoryItem.get("availableToPromiseTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("availableToPromiseTotal");
        BigDecimal qoh = inventoryItem.get("quantityOnHandTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("quantityOnHandTotal");
        Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", qoh.subtract(atp), "inventoryItemId", inventoryItem.get("inventoryItemId"), "userLogin", userLogin);
        try {
            Map<String, Object> result = dctx.getDispatcher().runSync("createInventoryItemDetail", createDetailMap);
            if (ServiceUtil.isError(result)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemDetailCreateProblem", UtilMisc.toMap("errorString", ""), locale), null, null, result);
            }
        } catch (GenericServiceException e1) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemDetailCreateProblem", UtilMisc.toMap("errorString", e1.getMessage()), locale));
        }
        try {
            inventoryItem.refresh();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemRefreshProblem", UtilMisc.toMap("errorString", e.getMessage()), locale));
        }
    }
    // set the fields on the item
    Map<String, Object> updateInventoryItemMap = UtilMisc.toMap("inventoryItemId", inventoryItem.getString("inventoryItemId"), "facilityId", inventoryTransfer.get("facilityIdTo"), "containerId", inventoryTransfer.get("containerIdTo"), "locationSeqId", inventoryTransfer.get("locationSeqIdTo"), "userLogin", userLogin);
    // for serialized items, automatically make them available
    if ("SERIALIZED_INV_ITEM".equals(inventoryType)) {
        updateInventoryItemMap.put("statusId", "INV_AVAILABLE");
    }
    // the inventory item is assigned to the new owner.
    if (destinationFacility != null && destinationFacility.get("ownerPartyId") != null) {
        String fromPartyId = inventoryItem.getString("ownerPartyId");
        String toPartyId = destinationFacility.getString("ownerPartyId");
        if (fromPartyId == null || !fromPartyId.equals(toPartyId)) {
            updateInventoryItemMap.put("ownerPartyId", toPartyId);
        }
    }
    try {
        Map<String, Object> result = dctx.getDispatcher().runSync("updateInventoryItem", updateInventoryItemMap);
        if (ServiceUtil.isError(result)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemStoreProblem", UtilMisc.toMap("errorString", ""), locale), null, null, result);
        }
    } catch (GenericServiceException exc) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemStoreProblem", UtilMisc.toMap("errorString", exc.getMessage()), locale));
    }
    // set the inventory transfer record to complete
    inventoryTransfer.set("statusId", "IXF_COMPLETE");
    // store the entities
    try {
        inventoryTransfer.store();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemStoreProblem", UtilMisc.toMap("errorString", e.getMessage()), 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) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal)

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