📄 uspsservices.java
字号:
return ServiceUtil.returnError("No packages found for ShipmentRouteSegment " + srsKeyString); } for (Iterator i = shipmentPackageRouteSegList.iterator(); i.hasNext();) { Document requestDocument = createUspsRequestDocument("DeliveryConfirmationV2.0Request"); Element requestElement = requestDocument.getDocumentElement(); UtilXml.addChildElementValue(requestElement, "Option", "3", requestDocument); UtilXml.addChildElement(requestElement, "ImageParameters", requestDocument); // From address if (UtilValidate.isNotEmpty(originAddress.getString("attnName"))) { UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("attnName"), requestDocument); UtilXml.addChildElementValue(requestElement, "FromFirm", originAddress.getString("toName"), requestDocument); } else { UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("toName"), requestDocument); } // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1 UtilXml.addChildElementValue(requestElement, "FromAddress1", originAddress.getString("address2"), requestDocument); UtilXml.addChildElementValue(requestElement, "FromAddress2", originAddress.getString("address1"), requestDocument); UtilXml.addChildElementValue(requestElement, "FromCity", originAddress.getString("city"), requestDocument); UtilXml.addChildElementValue(requestElement, "FromState", originAddress.getString("stateProvinceGeoId"), requestDocument); UtilXml.addChildElementValue(requestElement, "FromZip5", originAddress.getString("postalCode"), requestDocument); UtilXml.addChildElement(requestElement, "FromZip4", requestDocument); // To address if (UtilValidate.isNotEmpty(destinationAddress.getString("attnName"))) { UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("attnName"), requestDocument); UtilXml.addChildElementValue(requestElement, "ToFirm", destinationAddress.getString("toName"), requestDocument); } else { UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("toName"), requestDocument); } // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1 UtilXml.addChildElementValue(requestElement, "ToAddress1", destinationAddress.getString("address2"), requestDocument); UtilXml.addChildElementValue(requestElement, "ToAddress2", destinationAddress.getString("address1"), requestDocument); UtilXml.addChildElementValue(requestElement, "ToCity", destinationAddress.getString("city"), requestDocument); UtilXml.addChildElementValue(requestElement, "ToState", destinationAddress.getString("stateProvinceGeoId"), requestDocument); UtilXml.addChildElementValue(requestElement, "ToZip5", destinationAddress.getString("postalCode"), requestDocument); UtilXml.addChildElement(requestElement, "ToZip4", requestDocument); GenericValue shipmentPackageRouteSeg = (GenericValue) i.next(); GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage"); String spKeyString = "[" + shipmentPackage.getString("shipmentId") + "," + shipmentPackage.getString("shipmentPackageSeqId") + "]"; // WeightInOunces String weightStr = shipmentPackage.getString("weight"); if (UtilValidate.isEmpty(weightStr)) { return ServiceUtil.returnError("weight not found for ShipmentPackage " + spKeyString); } double weight = 0; try { weight = Double.parseDouble(weightStr); } catch (NumberFormatException nfe) { nfe.printStackTrace(); // TODO: handle exception } String weightUomId = shipmentPackage.getString("weightUomId"); if (UtilValidate.isEmpty(weightUomId)) { // assume weight is in pounds for consistency (this assumption is made in uspsDomesticRate also) weightUomId = "WT_lb"; } if (!"WT_oz".equals(weightUomId)) { // attempt a conversion to pounds GenericValue uomConversion = delegator.findByPrimaryKey("UomConversion", UtilMisc.toMap("uomId", weightUomId, "uomIdTo", "WT_oz")); if (uomConversion == null || UtilValidate.isEmpty(uomConversion.getString("conversionFactor"))) { return ServiceUtil.returnError("Unsupported weightUom [" + weightUomId + "] for ShipmentPackage " + spKeyString + ", could not find a conversion factor for WT_oz"); } weight *= uomConversion.getDouble("conversionFactor").doubleValue(); } DecimalFormat df = new DecimalFormat("#"); UtilXml.addChildElementValue(requestElement, "WeightInOunces", df.format(Math.ceil(weight)), requestDocument); UtilXml.addChildElementValue(requestElement, "ServiceType", serviceType, requestDocument); UtilXml.addChildElementValue(requestElement, "ImageType", "TIF", requestDocument); UtilXml.addChildElementValue(requestElement, "AddressServiceRequested", "True", requestDocument); Document responseDocument = null; try { responseDocument = sendUspsRequest("DeliveryConfirmationV2", requestDocument); } catch (UspsRequestException e) { Debug.log(e, module); return ServiceUtil.returnError("Error sending request for USPS Delivery Confirmation service: " + e.getMessage()); } Element responseElement = responseDocument.getDocumentElement(); Element respErrorElement = UtilXml.firstChildElement(responseElement, "Error"); if (respErrorElement != null) { return ServiceUtil.returnError("The following error was returned by the USPS Delivery Confirmation " + "service for ShipmentPackage " + spKeyString + ": " + UtilXml.childElementValue(respErrorElement, "Description")); } String labelImageString = UtilXml.childElementValue(responseElement, "DeliveryConfirmationLabel"); if (UtilValidate.isEmpty(labelImageString)) { return ServiceUtil.returnError("Incomplete response from the USPS Delivery Confirmation service: " + "missing or empty DeliveryConfirmationLabel element"); } shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes())); String trackingCode = UtilXml.childElementValue(responseElement, "DeliveryConfirmationNumber"); if (UtilValidate.isEmpty(trackingCode)) { return ServiceUtil.returnError("Incomplete response from the USPS Delivery Confirmation service: " + "missing or empty DeliveryConfirmationNumber element"); } shipmentPackageRouteSeg.set("trackingCode", trackingCode); shipmentPackageRouteSeg.store(); } } catch (GenericEntityException gee) { Debug.log(gee, module); return ServiceUtil.returnError("Error reading or writing shipment data for the USPS " + "Delivery Confirmation service: " + gee.getMessage()); } return ServiceUtil.returnSuccess(); } /* ------------------------------------------------------------------------------------------------------------- */ // testing utility service - remove this public static Map uspsDumpShipmentLabelImages(DispatchContext dctx, Map context) { GenericDelegator delegator = dctx.getDelegator(); try { String shipmentId = (String) context.get("shipmentId"); String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId"); GenericValue shipmentRouteSegment = delegator.findByPrimaryKey("ShipmentRouteSegment", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId)); List shipmentPackageRouteSegList = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId")); for (Iterator i = shipmentPackageRouteSegList.iterator(); i.hasNext();) { GenericValue shipmentPackageRouteSeg = (GenericValue) i.next(); byte[] labelImageBytes = shipmentPackageRouteSeg.getBytes("labelImage"); String outFileName = "UspsLabelImage" + shipmentRouteSegment.getString("shipmentId") + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + "_" + shipmentPackageRouteSeg.getString("shipmentPackageSeqId") + ".gif"; FileOutputStream fileOut = new FileOutputStream(outFileName); fileOut.write(labelImageBytes); fileOut.flush(); fileOut.close(); } } catch (GenericEntityException e) { Debug.log(e, module); return ServiceUtil.returnError(e.getMessage()); } catch (IOException e) { Debug.log(e, module); return ServiceUtil.returnError(e.getMessage()); } return ServiceUtil.returnSuccess(); } private static Document createUspsRequestDocument(String rootElement) { Document requestDocument = UtilXml.makeEmptyXmlDocument(rootElement); Element requestElement = requestDocument.getDocumentElement(); requestElement.setAttribute("USERID", UtilProperties.getPropertyValue("shipment.properties", "shipment.usps.access.userid")); requestElement.setAttribute("PASSWORD", UtilProperties.getPropertyValue("shipment.properties", "shipment.usps.access.password")); return requestDocument; } private static Document sendUspsRequest(String requestType, Document requestDocument) throws UspsRequestException { String conUrl = UtilProperties.getPropertyValue("shipment.properties", "shipment.usps.connect.url"); if (UtilValidate.isEmpty(conUrl)) { throw new UspsRequestException("Connection URL not specified; please check your configuration"); } OutputStream os = new ByteArrayOutputStream(); OutputFormat format = new OutputFormat(requestDocument); format.setOmitDocumentType(true); format.setOmitXMLDeclaration(true); format.setIndenting(false); XMLSerializer serializer = new XMLSerializer(os, format); try { serializer.asDOMSerializer(); serializer.serialize(requestDocument.getDocumentElement()); } catch (IOException e) { throw new UspsRequestException("Error serializing requestDocument: " + e.getMessage()); } String xmlString = os.toString(); Debug.logInfo("USPS XML request string: " + xmlString, module); String timeOutStr = UtilProperties.getPropertyValue("shipment.properties", "shipment.usps.connect.timeout", "60"); int timeout = 60; try { timeout = Integer.parseInt(timeOutStr); } catch (NumberFormatException e) { Debug.logError(e, "Unable to set timeout to " + timeOutStr + " using default " + timeout); } HttpClient http = new HttpClient(conUrl); http.setTimeout(timeout * 1000); http.setParameter("API", requestType); http.setParameter("XML", xmlString); String responseString = null; try { responseString = http.post(); } catch (HttpClientException e) { throw new UspsRequestException("Problem connecting with USPS server", e); } Debug.logInfo("USPS response: " + responseString, module); Document responseDocument = null; try { responseDocument = UtilXml.readXmlDocument(responseString, false); } catch (SAXException se) { throw new UspsRequestException("Error reading request Document from a String: " + se.getMessage()); } catch (ParserConfigurationException pce) { throw new UspsRequestException("Error reading request Document from a String: " + pce.getMessage()); } catch (IOException xmlReadException) { throw new UspsRequestException("Error reading request Document from a String: " + xmlReadException.getMessage()); } // If a top-level error document is returned, throw exception // Other request-level errors should be handled by the caller Element responseElement = responseDocument.getDocumentElement(); if ("Error".equals(responseElement.getNodeName())) { throw new UspsRequestException(UtilXml.childElementValue(responseElement, "Description")); } return responseDocument; }}class UspsRequestException extends GeneralException { UspsRequestException() { super(); } UspsRequestException(String msg) { super(msg); } UspsRequestException(Throwable t) { super(t); } UspsRequestException(String msg, Throwable t) { super(msg, t); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -