📄 uspsservices.java
字号:
/* * $Id: UspsServices.java 5462 2005-08-05 18:35:48Z jonesde $ * * Copyright (c) 2004 The Open For Business Project - www.ofbiz.org * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */package org.ofbiz.shipment.thirdparty.usps;import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.text.DecimalFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.ListIterator;import java.util.Map;import javax.xml.parsers.ParserConfigurationException;import org.ofbiz.base.util.*;import org.ofbiz.entity.GenericDelegator;import org.ofbiz.entity.GenericEntityException;import org.ofbiz.entity.GenericValue;import org.ofbiz.entity.util.EntityUtil;import org.ofbiz.product.store.ProductStoreWorker;import org.ofbiz.service.DispatchContext;import org.ofbiz.service.GenericServiceException;import org.ofbiz.service.LocalDispatcher;import org.ofbiz.service.ModelService;import org.ofbiz.service.ServiceUtil;import org.apache.xml.serialize.OutputFormat;import org.apache.xml.serialize.XMLSerializer;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.xml.sax.SAXException;/** * USPS Webtools API Services * * @author <a href="mailto:eckardjf@pobox.com">J. Eckard</a> * @version $Rev: 5462 $ * @since 3.2 */public class UspsServices { public final static String module = UspsServices.class.getName(); public static Map uspsRateInquire(DispatchContext dctx, Map context) { GenericDelegator delegator = dctx.getDelegator(); // check for 0 weight Double shippableWeight = (Double) context.get("shippableWeight"); if (shippableWeight.doubleValue() == 0) { // TODO: should we return an error, or $0.00 ? } // get the origination ZIP String originationZip = null; GenericValue productStore = ProductStoreWorker.getProductStore(((String) context.get("productStoreId")), delegator); if (productStore != null && productStore.get("inventoryFacilityId") != null) { try { List shipLocs = delegator.findByAnd("FacilityContactMechPurpose", UtilMisc.toMap("facilityId", productStore.getString("inventoryFacilityId"), "contactMechPurposeTypeId", "SHIP_ORIG_LOCATION"), UtilMisc.toList("-fromDate")); if (UtilValidate.isNotEmpty(shipLocs)) { shipLocs = EntityUtil.filterByDate(shipLocs); GenericValue purp = EntityUtil.getFirst(shipLocs); if (purp != null) { GenericValue shipFromAddress = delegator.findByPrimaryKey("PostalAddress", UtilMisc.toMap("contactMechId", purp.getString("contactMechId"))); if (shipFromAddress != null) { originationZip = shipFromAddress.getString("postalCode"); } } } } catch (GenericEntityException e) { Debug.logError(e, module); } } if (UtilValidate.isEmpty(originationZip)) { return ServiceUtil.returnError("Unable to determine the origination ZIP"); } // get the destination ZIP String destinationZip = null; String shippingContactMechId = (String) context.get("shippingContactMechId"); if (UtilValidate.isNotEmpty(shippingContactMechId)) { try { GenericValue shipToAddress = delegator.findByPrimaryKey("PostalAddress", UtilMisc.toMap("contactMechId", shippingContactMechId)); if (shipToAddress != null) { destinationZip = shipToAddress.getString("postalCode"); } } catch (GenericEntityException e) { Debug.logError(e, module); } } if (UtilValidate.isEmpty(destinationZip)) { return ServiceUtil.returnError("Unable to determine the destination ZIP"); } // get the service code String serviceCode = null; try { GenericValue carrierShipmentMethod = delegator.findByPrimaryKey("CarrierShipmentMethod", UtilMisc.toMap("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId", (String) context.get("carrierPartyId"), "roleTypeId", (String) context.get("carrierRoleTypeId"))); if (carrierShipmentMethod != null) { serviceCode = carrierShipmentMethod.getString("carrierServiceCode"); } } catch (GenericEntityException e) { Debug.logError(e, module); } if (UtilValidate.isEmpty(serviceCode)) { return ServiceUtil.returnError("Unable to determine the service code"); } // create the request document Document requestDocument = createUspsRequestDocument("RateRequest"); // TODO: 70 lb max is valid for Express, Priority and Parcel only - handle other methods double maxWeight = 70; String maxWeightStr = UtilProperties.getPropertyValue((String) context.get("serviceConfigProps"), "shipment.usps.max.estimate.weight", "70"); try { maxWeight = Double.parseDouble(maxWeightStr); } catch (NumberFormatException e) { Debug.logWarning("Error parsing max estimate weight string [" + maxWeightStr + "], using default instead", module); maxWeight = 70; } List shippableItemInfo = (List) context.get("shippableItemInfo"); List packages = getPackageSplit(shippableItemInfo, maxWeight); // TODO: Up to 25 packages can be included per request - handle more than 25 for (ListIterator li = packages.listIterator(); li.hasNext();) { Map packageMap = (Map) li.next(); double packageWeight = calcPackageWeight(packageMap, shippableItemInfo, 0); if (packageWeight == 0) { continue; } Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package", requestDocument); packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples) UtilXml.addChildElementValue(packageElement, "Service", serviceCode, requestDocument); UtilXml.addChildElementValue(packageElement, "ZipOrigination", originationZip, requestDocument); UtilXml.addChildElementValue(packageElement, "ZipDestination", destinationZip, requestDocument); double weightPounds = Math.floor(packageWeight); UtilXml.addChildElementValue(packageElement, "Pounds", String.valueOf(weightPounds), requestDocument); double weightOunces = Math.ceil(packageWeight % weightPounds * 16); UtilXml.addChildElementValue(packageElement, "Ounces", String.valueOf(weightOunces), requestDocument); // TODO: handle other container types, package sizes, and machinabile packages UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument); UtilXml.addChildElementValue(packageElement, "Size", "Regular", requestDocument); UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument); } // send the request Document responseDocument = null; try { responseDocument = sendUspsRequest("Rate", requestDocument); } catch (UspsRequestException e) { Debug.log(e, module); return ServiceUtil.returnError("Error sending request for USPS Domestic Rate Calculation service: " + e.getMessage()); } List rates = UtilXml.childElementList(responseDocument.getDocumentElement(), "Package"); if (UtilValidate.isEmpty(rates)) { return ServiceUtil.returnError("No rate available at this time"); } double estimateAmount = 0.00; for (Iterator i = rates.iterator(); i.hasNext();) { Element packageElement = (Element) i.next(); try { double packageAmount = Double.parseDouble(UtilXml.childElementValue(packageElement, "Postage")); estimateAmount += packageAmount; } catch (NumberFormatException e) { Debug.log(e, module); } } Map result = ServiceUtil.returnSuccess(); result.put("shippingEstimateAmount", new Double(estimateAmount)); return result; } // lifted from UpsServices with no changes - 2004.09.06 JFE private static List getPackageSplit(List shippableItemInfo, double maxWeight) { // create the package list w/ the first pacakge List packages = new LinkedList(); if (shippableItemInfo != null) { Iterator sii = shippableItemInfo.iterator(); while (sii.hasNext()) { Map itemInfo = (Map) sii.next(); long pieces = ((Long) itemInfo.get("piecesIncluded")).longValue(); double totalQuantity = ((Double) itemInfo.get("quantity")).doubleValue(); double totalWeight = ((Double) itemInfo.get("weight")).doubleValue(); String productId = (String) itemInfo.get("productId"); // sanity check if (pieces < 1) { pieces = 1; // can NEVER be less than one } double weight = totalWeight / pieces; for (int z = 1; z <= totalQuantity; z++) { double partialQty = pieces > 1 ? 1.000 / pieces : 1; for (long x = 0; x < pieces; x++) { if (weight >= maxWeight) { Map newPackage = new HashMap(); newPackage.put(productId, new Double(partialQty)); packages.add(newPackage); } else if (totalWeight > 0) { // create the first package if (packages.size() == 0) { packages.add(new HashMap()); } // package loop int packageSize = packages.size(); boolean addedToPackage = false; for (int pi = 0; pi < packageSize; pi++) { if (!addedToPackage) { Map packageMap = (Map) packages.get(pi); double packageWeight = calcPackageWeight(packageMap, shippableItemInfo, weight); if (packageWeight <= maxWeight) { Double qtyD = (Double) packageMap.get(productId); double qty = qtyD == null ? 0 : qtyD.doubleValue(); packageMap.put(productId, new Double(qty + partialQty)); addedToPackage = true; } } } if (!addedToPackage) { Map packageMap = new HashMap(); packageMap.put(productId, new Double(partialQty)); packages.add(packageMap); } } } } } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -