📄 dhlservices.java
字号:
String templateName = UtilProperties.getPropertyValue(shipmentPropertiesFile, "shipment.template.dhl.rate.estimate"); if ((templateName == null) || (templateName.trim().length() == 0)) { return ServiceUtil.returnError("Cannot get DHL Estimate: DHL Rate template not configured (shipment.template.dhl.rate.estimate"); } StringWriter outWriter = new StringWriter(); Map inContext = new HashMap(); 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")); inContext.put("postalCode", destPostalAddress.getString("postalCode")); inContext.put("phoneNbr", destPhoneNumber); inContext.put("labelImageType", labelImagePreference); try { Map tmpResult = ContentWorker.renderContentAsText(delegator, templateName, outWriter, inContext, null, locale, "text/plain"); } catch (Exception e) { Debug.logError(e, "Cannot confirm DHL shipment: Failed to render DHL XML Request.", module); return ServiceUtil.returnError("Cannot confirm DHL shipment: Failed to render DHL XML Request."); } String requestString = outWriter.toString(); if (Debug.verboseOn()) { Debug.logVerbose(requestString, module); } // send the request String responseString = null; try { responseString = sendDhlRequest(requestString); 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(uceErrMsg); } // pass to handler method return handleDhlShipmentConfirmResponse(responseString, shipmentRouteSegment, shipmentPackageRouteSegs); } catch (GenericEntityException e) { Debug.logError(e, module); if (shipmentConfirmResponseString != null) { Debug.logError("Got XML ShipmentConfirmRespose: " + shipmentConfirmResponseString, module); return ServiceUtil.returnError(UtilMisc.toList( "Error reading or writing Shipment data for DHL Shipment Confirm: " + e.toString(), "A ShipmentConfirmRespose was received: " + shipmentConfirmResponseString)); } else { return ServiceUtil.returnError("Error reading or writing Shipment data for DHL Shipment Confirm: " + e.toString()); } } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError("Error reading or writing Shipment data for DHL Shipment Confirm: " + e.toString()); } } // NOTE: Must VOID shipments on errors public static Map handleDhlShipmentConfirmResponse(String rateResponseString, GenericValue shipmentRouteSegment, List shipmentPackageRouteSegs) throws GenericEntityException { Map result = new HashMap(); GenericValue shipmentPackageRouteSeg = (GenericValue) 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("Cannot get response DHL shipment label for shipment package route segment " + shipmentPackageRouteSeg + ". DHL response is: " + rateResponseString); } // 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(); StringBuffer sb = new StringBuffer(); 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()); if (labelBytes != null) { // store in db blob shipmentPackageRouteSeg.setBytes("labelImage", labelBytes); } else { Debug.log("Failed to either decode returned DHL label or no data found in eCommerce/Shipment/Label/Image."); // 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("DHL Shipment Confirmed."); } private static double getWeight(List shippableItemInfo) { double totalWeight = 0; if (shippableItemInfo != null) { Iterator sii = shippableItemInfo.iterator(); while (sii.hasNext()) { Map itemInfo = (Map) sii.next(); double weight = ((Double) itemInfo.get("weight")).doubleValue(); totalWeight = totalWeight + weight; } } return totalWeight; } public static Document createAccessRequestDocument() { return createAccessRequestDocument(shipmentPropertiesFile); } public static Document createAccessRequestDocument(String props) { Document eCommerceRequestDocument = UtilXml .makeEmptyXmlDocument("eCommerce"); Element eCommerceRequesElement = eCommerceRequestDocument .getDocumentElement(); eCommerceRequesElement.setAttribute("version", UtilProperties .getPropertyValue(props, "shipment.dhl.head.version")); eCommerceRequesElement.setAttribute("action", UtilProperties .getPropertyValue(props, "shipment.dhl.head.action")); Element requestorRequestElement = UtilXml.addChildElement( eCommerceRequesElement, "Requestor", eCommerceRequestDocument); UtilXml .addChildElementValue(requestorRequestElement, "ID", UtilProperties.getPropertyValue(props, "shipment.dhl.access.userid"), eCommerceRequestDocument); UtilXml.addChildElementValue(requestorRequestElement, "Password", UtilProperties.getPropertyValue(props, "shipment.dhl.access.password"), eCommerceRequestDocument); return eCommerceRequestDocument; } public static void handleErrors(Element responseElement, List errorList) { Element faultsElement = UtilXml.firstChildElement(responseElement, "Faults"); List faultElements = UtilXml.childElementList(faultsElement, "Fault"); if (UtilValidate.isNotEmpty(faultElements)) { Iterator errorElementIter = faultElements.iterator(); while (errorElementIter.hasNext()) { StringBuffer errorMessageBuf = new StringBuffer(); Element errorElement = (Element) errorElementIter.next(); String errorCode = UtilXml.childElementValue(errorElement, "Code"); String errorDescription = UtilXml.childElementValue( errorElement, "Desc"); String errorSource = UtilXml.childElementValue(errorElement, "Source"); if (UtilValidate.isEmpty(errorSource)) { errorSource = UtilXml.childElementValue(errorElement, "Context"); } errorMessageBuf.append("An error occurred [code:"); errorMessageBuf.append(errorCode); errorMessageBuf.append("] "); errorMessageBuf.append(" [Description:"); errorMessageBuf.append(errorDescription); errorMessageBuf.append("] "); errorMessageBuf.append(". "); if (UtilValidate.isNotEmpty(errorSource)) { errorMessageBuf.append("The error was at Element ["); errorMessageBuf.append(errorSource); errorMessageBuf.append("]"); } errorList.add(errorMessageBuf.toString()); } } }}class DhlConnectException extends GeneralException { DhlConnectException() { super(); } DhlConnectException(String msg) { super(msg); } DhlConnectException(Throwable t) { super(t); } DhlConnectException(String msg, Throwable t) { super(msg, t); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -