Author: doogie
Date: Sat Mar 21 23:47:53 2009 New Revision: 757101 URL: http://svn.apache.org/viewvc?rev=757101&view=rev Log: Fix purely empty whitespace lines, and remove trailing whitespace. Modified: ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ImportOrdersFromEbay.java ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ProductsExportToEbay.java Modified: ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ImportOrdersFromEbay.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ImportOrdersFromEbay.java?rev=757101&r1=757100&r2=757101&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ImportOrdersFromEbay.java (original) +++ ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ImportOrdersFromEbay.java Sat Mar 21 23:47:53 2009 @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -62,10 +62,10 @@ import org.w3c.dom.Element; public class ImportOrdersFromEbay { - + private static final String resource = "EbayUiLabels"; private static final String module = ImportOrdersFromEbay.class.getName(); - + public static Map importOrdersSearchFromEbay(DispatchContext dctx, Map context) { GenericDelegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); @@ -73,45 +73,45 @@ Map result = FastMap.newInstance(); try { String configString = "ebayExport.properties"; - + // get the Developer Key String devID = UtilProperties.getPropertyValue(configString, "eBayExport.devID"); - + // get the Application Key String appID = UtilProperties.getPropertyValue(configString, "eBayExport.appID"); - + // get the Certifcate Key String certID = UtilProperties.getPropertyValue(configString, "eBayExport.certID"); - + // get the Token String token = UtilProperties.getPropertyValue(configString, "eBayExport.token"); - + // get the Compatibility Level String compatibilityLevel = UtilProperties.getPropertyValue(configString, "eBayExport.compatibilityLevel"); - + // get the Site ID String siteID = UtilProperties.getPropertyValue(configString, "eBayExport.siteID"); - + // get the xmlGatewayUri String xmlGatewayUri = UtilProperties.getPropertyValue(configString, "eBayExport.xmlGatewayUri"); - + StringBuffer sellerTransactionsItemsXml = new StringBuffer(); - - if (!ServiceUtil.isFailure(buildGetSellerTransactionsRequest(context, sellerTransactionsItemsXml, token))) { + + if (!ServiceUtil.isFailure(buildGetSellerTransactionsRequest(context, sellerTransactionsItemsXml, token))) { result = postItem(xmlGatewayUri, sellerTransactionsItemsXml, devID, appID, certID, "GetSellerTransactions", compatibilityLevel, siteID); String success = (String)result.get(ModelService.SUCCESS_MESSAGE); - if (success != null) { + if (success != null) { result = checkOrders(delegator, dispatcher, locale, context, success); } } - } catch (Exception e) { + } catch (Exception e) { Debug.logError("Exception in importOrdersSearchFromEbay " + e, module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionInImportOrdersSearchFromEbay", locale)); } - + return result; } - + public static Map importOrderFromEbay(DispatchContext dctx, Map context) { GenericDelegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); @@ -135,7 +135,7 @@ order.put("amountPaid", (String) context.get("amountPaid")); order.put("paidTime", (String) context.get("paidTime")); order.put("shippedTime", (String) context.get("shippedTime")); - + order.put("buyerName", (String) context.get("buyerName")); order.put("emailBuyer", (String) context.get("emailBuyer")); order.put("shippingAddressPhone", (String) context.get("shippingAddressPhone")); @@ -146,29 +146,29 @@ order.put("shippingAddressCountry", (String) context.get("shippingAddressCountry")); order.put("shippingAddressStateOrProvince", (String) context.get("shippingAddressStateOrProvince")); order.put("shippingAddressCityName", (String) context.get("shippingAddressCityName")); - + result = createShoppingCart(delegator, dispatcher, locale, order, true); - } catch (Exception e) { + } catch (Exception e) { Debug.logError("Exception in importOrderFromEbay " + e, module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionInImportOrderFromEbay", locale)); } - + return result; } - + public static Map setEbayOrderToComplete(DispatchContext dctx, Map context) { GenericDelegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String orderId = (String) context.get("orderId"); String externalId = (String) context.get("externalId"); String transactionId = (String) context.get("transactionId"); - Map result = FastMap.newInstance(); + Map result = FastMap.newInstance(); try { if (orderId == null && externalId == null) { Debug.logError("orderId or externalId must be filled", module); - return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.orderIdOrExternalIdAreMandatory", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.orderIdOrExternalIdAreMandatory", locale)); } - + GenericValue orderHeader = null; if (UtilValidate.isNotEmpty(orderId)) { // Get the order header and verify if this order has been imported @@ -176,60 +176,60 @@ orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId)); if (orderHeader == null) { Debug.logError("Cannot find order with orderId [" + orderId + "]", module); - return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.errorRetrievingOrderFromOrderId", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.errorRetrievingOrderFromOrderId", locale)); } - + if (!"EBAY_SALES_CHANNEL".equals(orderHeader.getString("salesChannelEnumId")) || orderHeader.getString("externalId") == null) { // This order was not imported from eBay: there is nothing to do. return ServiceUtil.returnSuccess(); } - + // get externalId and transactionId from OrderHeader externalId = (String)orderHeader.get("externalId"); transactionId = (String)orderHeader.get("transactionId"); } - + String configString = "ebayExport.properties"; - + // get the Developer Key String devID = UtilProperties.getPropertyValue(configString, "eBayExport.devID"); - + // get the Application Key String appID = UtilProperties.getPropertyValue(configString, "eBayExport.appID"); - + // get the Certifcate Key String certID = UtilProperties.getPropertyValue(configString, "eBayExport.certID"); - + // get the Token String token = UtilProperties.getPropertyValue(configString, "eBayExport.token"); - + // get the Compatibility Level String compatibilityLevel = UtilProperties.getPropertyValue(configString, "eBayExport.compatibilityLevel"); - + // get the Site ID String siteID = UtilProperties.getPropertyValue(configString, "eBayExport.siteID"); - + // get the xmlGatewayUri String xmlGatewayUri = UtilProperties.getPropertyValue(configString, "eBayExport.xmlGatewayUri"); StringBuffer completeSaleXml = new StringBuffer(); - - if (!ServiceUtil.isFailure(buildCompleteSaleRequest(delegator, locale, externalId, transactionId, context, completeSaleXml, token))) { + + if (!ServiceUtil.isFailure(buildCompleteSaleRequest(delegator, locale, externalId, transactionId, context, completeSaleXml, token))) { result = postItem(xmlGatewayUri, completeSaleXml, devID, appID, certID, "CompleteSale", compatibilityLevel, siteID); String successMessage = (String)result.get("successMessage"); - if (successMessage != null) { + if (successMessage != null) { return readCompleteSaleResponse(successMessage, locale); } else{ ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.errorDuringPostCompleteSaleRequest", locale)); - } + } } - } catch (Exception e) { + } catch (Exception e) { Debug.logError("Exception in setEbayOrderToComplete " + e, module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.exceptionInSetEbayOrderToComplete", locale)); } return ServiceUtil.returnSuccess(); } - + private static String toString(InputStream inputStream) throws IOException { String string; StringBuilder outputBuilder = new StringBuilder(); @@ -241,13 +241,13 @@ } return outputBuilder.toString(); } - - private static Map postItem(String postItemsUrl, StringBuffer dataItems, String devID, String appID, String certID, + + private static Map postItem(String postItemsUrl, StringBuffer dataItems, String devID, String appID, String certID, String callName, String compatibilityLevel, String siteID) throws IOException { if (Debug.verboseOn()) { Debug.logVerbose("Request of " + callName + " To eBay:\n" + dataItems.toString(), module); } - + HttpURLConnection connection = (HttpURLConnection)(new URL(postItemsUrl)).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); @@ -259,16 +259,16 @@ connection.setRequestProperty("X-EBAY-API-CALL-NAME", callName); connection.setRequestProperty("X-EBAY-API-SITEID", siteID); connection.setRequestProperty("Content-Type", "text/xml"); - + OutputStream outputStream = connection.getOutputStream(); outputStream.write(dataItems.toString().getBytes()); outputStream.close(); - + int responseCode = connection.getResponseCode(); InputStream inputStream = null; Map result = FastMap.newInstance(); String response = null; - + if (responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); @@ -278,14 +278,14 @@ inputStream = connection.getErrorStream(); result = ServiceUtil.returnFailure(toString(inputStream)); } - + if (Debug.verboseOn()) { Debug.logVerbose("Response of " + callName + " From eBay:\n" + response, module); } - + return result; } - + private static Map checkOrders(GenericDelegator delegator, LocalDispatcher dispatcher, Locale locale, Map context, String response) { StringBuffer errorMessage = new StringBuffer(); List orders = readResponseFromEbay(response, locale, (String)context.get("productStoreId"), delegator, errorMessage); @@ -295,7 +295,7 @@ } else if (orders.size() == 0) { Debug.logError("No orders found", module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.noOrdersFound", locale)); - } else { + } else { Iterator orderIter = orders.iterator(); while (orderIter.hasNext()) { Map order = (Map)orderIter.next(); @@ -315,7 +315,7 @@ return result; } } - + private static Map buildGetSellerTransactionsRequest(Map context, StringBuffer dataItemsXml, String token) { Locale locale = (Locale)context.get("locale"); String fromDate = (String)context.get("fromDate"); @@ -324,10 +324,10 @@ Document transDoc = UtilXml.makeEmptyXmlDocument("GetSellerTransactionsRequest"); Element transElem = transDoc.getDocumentElement(); transElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); - + appendRequesterCredentials(transElem, transDoc, token); UtilXml.addChildElementValue(transElem, "DetailLevel", "ReturnAll", transDoc); - + String fromDateOut = convertDate(fromDate, "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); if (fromDateOut != null) { UtilXml.addChildElementValue(transElem, "ModTimeFrom", fromDateOut, transDoc); @@ -335,8 +335,8 @@ Debug.logError("Cannot convert from date from yyyy-MM-dd HH:mm:ss.SSS date format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z' date format", module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.cannotConvertFromDate", locale)); } - - + + fromDateOut = convertDate(thruDate, "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); if (fromDateOut != null) { UtilXml.addChildElementValue(transElem, "ModTimeTo", fromDateOut, transDoc); @@ -344,7 +344,7 @@ Debug.logError("Cannot convert thru date from yyyy-MM-dd HH:mm:ss.SSS date format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z' date format", module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.cannotConvertThruDate", locale)); } - + dataItemsXml.append(UtilXml.writeXmlDocument(transDoc)); } catch (Exception e) { Debug.logError("Exception during building get seller transactions request", module); @@ -352,14 +352,14 @@ } return ServiceUtil.returnSuccess(); } - + private static Map buildGetEbayDetailsRequest(Map context, StringBuffer dataItemsXml, String token) { Locale locale = (Locale)context.get("locale"); try { Document transDoc = UtilXml.makeEmptyXmlDocument("GeteBayDetailsRequest"); Element transElem = transDoc.getDocumentElement(); transElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); - + appendRequesterCredentials(transElem, transDoc, token); UtilXml.addChildElementValue(transElem, "DetailName", "ShippingServiceDetails", transDoc); UtilXml.addChildElementValue(transElem, "DetailName", "TaxJurisdiction", transDoc); @@ -370,11 +370,11 @@ } return ServiceUtil.returnSuccess(); } - + public static Map buildCompleteSaleRequest(GenericDelegator delegator, Locale locale, String itemId, String transactionId, Map context, StringBuffer dataItemsXml, String token) { String paid = (String)context.get("paid"); String shipped = (String)context.get("shipped"); - + try { if (itemId == null || transactionId == null) { Debug.logError("Cannot be retrieve itemId and transactionId from externalId", module); @@ -384,17 +384,17 @@ Document transDoc = UtilXml.makeEmptyXmlDocument("CompleteSaleRequest"); Element transElem = transDoc.getDocumentElement(); transElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); - + appendRequesterCredentials(transElem, transDoc, token); - + UtilXml.addChildElementValue(transElem, "ItemID", itemId, transDoc); - + // default shipped = Y (call from eca during order completed) if (paid == null && shipped == null) { shipped = "Y"; } - - // Set item id to paid or not paid + + // Set item id to paid or not paid if (UtilValidate.isNotEmpty(paid)) { if ("Y".equals(paid)) { paid = "true"; @@ -404,7 +404,7 @@ UtilXml.addChildElementValue(transElem, "Paid", paid, transDoc); } - // Set item id to shipped or not shipped + // Set item id to shipped or not shipped if (UtilValidate.isNotEmpty(shipped)) { if ("Y".equals(shipped)) { shipped = "true"; @@ -413,9 +413,9 @@ } UtilXml.addChildElementValue(transElem, "Shipped", shipped, transDoc); } - + UtilXml.addChildElementValue(transElem, "TransactionID", transactionId, transDoc); - + dataItemsXml.append(UtilXml.writeXmlDocument(transDoc)); } catch (Exception e) { Debug.logError("Exception during building complete sale request", module); @@ -423,12 +423,12 @@ } return ServiceUtil.returnSuccess(); } - + private static void appendRequesterCredentials(Element elem, Document doc, String token) { Element requesterCredentialsElem = UtilXml.addChildElement(elem, "RequesterCredentials", doc); UtilXml.addChildElementValue(requesterCredentialsElem, "eBayAuthToken", token, doc); } - + private static Map readCompleteSaleResponse(String msg, Locale locale) { try { Document docResponse = UtilXml.readXmlDocument(msg, true); @@ -449,7 +449,7 @@ } return ServiceUtil.returnSuccess(); } - + private static List readResponseFromEbay(String msg, Locale locale, String productStoreId, GenericDelegator delegator, StringBuffer errorMessage) { List orders = null; try { @@ -457,7 +457,7 @@ Element elemResponse = docResponse.getDocumentElement(); String ack = UtilXml.childElementValue(elemResponse, "Ack", "Failure"); List paginationList = UtilXml.childElementList(elemResponse, "PaginationResult"); - + int totalOrders = 0; Iterator paginationElemIter = paginationList.iterator(); while (paginationElemIter.hasNext()) { @@ -465,26 +465,26 @@ String totalNumberOfEntries = UtilXml.childElementValue(paginationElement, "TotalNumberOfEntries", "0"); totalOrders = new Integer(totalNumberOfEntries).intValue(); } - + if (ack != null && "Success".equals(ack)) { orders = new ArrayList(); - if (totalOrders > 0) { + if (totalOrders > 0) { // retrieve transaction array List transactions = UtilXml.childElementList(elemResponse, "TransactionArray"); Iterator transactionsElemIter = transactions.iterator(); while (transactionsElemIter.hasNext()) { Element transactionsElement = (Element) transactionsElemIter.next(); - + // retrieve transaction List transaction = UtilXml.childElementList(transactionsElement, "Transaction"); Iterator transactionElemIter = transaction.iterator(); while (transactionElemIter.hasNext()) { Map order = FastMap.newInstance(); String itemId = ""; - + Element transactionElement = (Element) transactionElemIter.next(); order.put("amountPaid", UtilXml.childElementValue(transactionElement, "AmountPaid", "0")); - + // retrieve buyer List buyer = UtilXml.childElementList(transactionElement, "Buyer"); Iterator buyerElemIter = buyer.iterator(); @@ -493,13 +493,13 @@ order.put("emailBuyer", UtilXml.childElementValue(buyerElement, "Email", "")); order.put("eiasTokenBuyer", UtilXml.childElementValue(buyerElement, "EIASToken", "")); order.put("ebayUserIdBuyer", UtilXml.childElementValue(buyerElement, "UserID", "")); - + // retrieve buyer information List buyerInfo = UtilXml.childElementList(buyerElement, "BuyerInfo"); Iterator buyerInfoElemIter = buyerInfo.iterator(); while (buyerInfoElemIter.hasNext()) { Element buyerInfoElement = (Element)buyerInfoElemIter.next(); - + // retrieve shipping address List shippingAddressInfo = UtilXml.childElementList(buyerInfoElement, "ShippingAddress"); Iterator shippingAddressElemIter = shippingAddressInfo.iterator(); @@ -518,7 +518,7 @@ } } } - + // retrieve shipping details List shippingDetails = UtilXml.childElementList(transactionElement, "ShippingDetails"); Iterator shippingDetailsElemIter = shippingDetails.iterator(); @@ -527,7 +527,7 @@ order.put("insuranceFee", UtilXml.childElementValue(shippingDetailsElement, "InsuranceFee", "0")); order.put("insuranceOption", UtilXml.childElementValue(shippingDetailsElement, "InsuranceOption", "")); order.put("insuranceWanted", UtilXml.childElementValue(shippingDetailsElement, "InsuranceWanted", "false")); - + // retrieve sales Tax List salesTax = UtilXml.childElementList(shippingDetailsElement, "SalesTax"); Iterator salesTaxElemIter = salesTax.iterator(); @@ -536,30 +536,30 @@ order.put("salesTaxAmount", UtilXml.childElementValue(salesTaxElement, "SalesTaxAmount", "0")); order.put("salesTaxPercent", UtilXml.childElementValue(salesTaxElement, "SalesTaxPercent", "0")); order.put("salesTaxState", UtilXml.childElementValue(salesTaxElement, "SalesTaxState", "0")); - order.put("shippingIncludedInTax", UtilXml.childElementValue(salesTaxElement, "ShippingIncludedInTax", "false")); + order.put("shippingIncludedInTax", UtilXml.childElementValue(salesTaxElement, "ShippingIncludedInTax", "false")); } - + // retrieve tax table List taxTable = UtilXml.childElementList(shippingDetailsElement, "TaxTable"); Iterator taxTableElemIter = taxTable.iterator(); while (taxTableElemIter.hasNext()) { Element taxTableElement = (Element)taxTableElemIter.next(); - + List taxJurisdiction = UtilXml.childElementList(taxTableElement, "TaxJurisdiction"); Iterator taxJurisdictionElemIter = taxJurisdiction.iterator(); while (taxJurisdictionElemIter.hasNext()) { Element taxJurisdictionElement = (Element)taxJurisdictionElemIter.next(); - + order.put("jurisdictionID", UtilXml.childElementValue(taxJurisdictionElement, "JurisdictionID", "")); order.put("jurisdictionSalesTaxPercent", UtilXml.childElementValue(taxJurisdictionElement, "SalesTaxPercent", "0")); order.put("jurisdictionShippingIncludedInTax", UtilXml.childElementValue(taxJurisdictionElement, "ShippingIncludedInTax", "0")); } } } - + // retrieve created date order.put("createdDate", UtilXml.childElementValue(transactionElement, "CreatedDate", "")); - + // retrieve item List item = UtilXml.childElementList(transactionElement, "Item"); Iterator itemElemIter = item.iterator(); @@ -570,13 +570,13 @@ order.put("quantity", UtilXml.childElementValue(itemElement, "Quantity", "0")); order.put("startPrice", UtilXml.childElementValue(itemElement, "StartPrice", "0")); order.put("title", UtilXml.childElementValue(itemElement, "Title", "")); - + String productId = UtilXml.childElementValue(itemElement, "SKU", ""); if (UtilValidate.isEmpty(productId)) { productId = retrieveProductIdFromTitle(delegator, (String)order.get("title")); } order.put("productId", productId); - + // retrieve selling status List sellingStatus = UtilXml.childElementList(itemElement, "SellingStatus"); Iterator sellingStatusitemElemIter = sellingStatus.iterator(); @@ -587,10 +587,10 @@ order.put("listingStatus", UtilXml.childElementValue(sellingStatusElement, "ListingStatus", "")); } } - + // retrieve quantity purchased order.put("quantityPurchased", UtilXml.childElementValue(transactionElement, "QuantityPurchased", "0")); - + // retrieve status List status = UtilXml.childElementList(transactionElement, "Status"); Iterator statusElemIter = status.iterator(); @@ -602,24 +602,24 @@ order.put("completeStatus", UtilXml.childElementValue(statusElement, "CompleteStatus", "")); order.put("buyerSelectedShipping", UtilXml.childElementValue(statusElement, "BuyerSelectedShipping", "")); } - + // retrieve transactionId String transactionId = UtilXml.childElementValue(transactionElement, "TransactionID", ""); - + // set the externalId and transactionId order.put("externalId", itemId); order.put("transactionId", transactionId); - + GenericValue orderExist = externalOrderExists(delegator, itemId, transactionId); if (orderExist != null) { - order.put("orderId", (String)orderExist.get("orderId")); + order.put("orderId", (String)orderExist.get("orderId")); } else { order.put("orderId", ""); } - + // retrieve transaction price order.put("transactionPrice", UtilXml.childElementValue(transactionElement, "TransactionPrice", "0")); - + // retrieve external transaction List externalTransaction = UtilXml.childElementList(transactionElement, "ExternalTransaction"); Iterator externalTransactionElemIter = externalTransaction.iterator(); @@ -630,7 +630,7 @@ order.put("feeOrCreditAmount", UtilXml.childElementValue(externalTransactionElement, "FeeOrCreditAmount", "0")); order.put("paymentOrRefundAmount", UtilXml.childElementValue(externalTransactionElement, "PaymentOrRefundAmount", "0")); } - + // retrieve shipping service selected List shippingServiceSelected = UtilXml.childElementList(transactionElement, "ShippingServiceSelected"); Iterator shippingServiceSelectedElemIter = shippingServiceSelected.iterator(); @@ -638,40 +638,40 @@ Element shippingServiceSelectedElement = (Element)shippingServiceSelectedElemIter.next(); order.put("shippingService", UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingService", "")); order.put("shippingServiceCost", UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingServiceCost", "0")); - + String incuranceCost = UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingInsuranceCost", "0"); String additionalCost = UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingServiceAdditionalCost", "0"); String surchargeCost = UtilXml.childElementValue(shippingServiceSelectedElement, "ShippingSurcharge", "0"); - + double shippingInsuranceCost = 0; double shippingServiceAdditionalCost = 0; double shippingSurcharge = 0; - + if (UtilValidate.isNotEmpty(incuranceCost)) { shippingInsuranceCost = new Double(incuranceCost).doubleValue(); } - + if (UtilValidate.isNotEmpty(additionalCost)) { shippingServiceAdditionalCost = new Double(additionalCost).doubleValue(); } - + if (UtilValidate.isNotEmpty(surchargeCost)) { shippingSurcharge = new Double(surchargeCost).doubleValue(); } - + double shippingTotalAdditionalCost = shippingInsuranceCost + shippingServiceAdditionalCost + shippingSurcharge; String totalAdditionalCost = new Double(shippingTotalAdditionalCost).toString(); order.put("shippingTotalAdditionalCost", totalAdditionalCost); } - + // retrieve paid time order.put("paidTime", UtilXml.childElementValue(transactionElement, "PaidTime", "")); - + // retrieve shipped time order.put("shippedTime", UtilXml.childElementValue(transactionElement, "ShippedTime", "")); - + order.put("productStoreId", productStoreId); - + orders.add(order); } } @@ -689,7 +689,7 @@ } return orders; } - + private static Map createShoppingCart(GenericDelegator delegator, LocalDispatcher dispatcher, Locale locale, Map parameters, boolean create) { try { String productStoreId = (String) parameters.get("productStoreId"); @@ -697,10 +697,10 @@ String defaultCurrencyUomId = ""; String payToPartyId = ""; String facilityId = ""; - + // Product Store is mandatory if (productStoreId == null) { - return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productStoreIdIsMandatory", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productStoreIdIsMandatory", locale)); } else { GenericValue productStore = delegator.findByPrimaryKey("ProductStore", UtilMisc.toMap("productStoreId", productStoreId)); if (productStore != null) { @@ -711,45 +711,45 @@ return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productStoreIdIsMandatory", locale)); } } - + // create a new shopping cart ShoppingCart cart = new ShoppingCart(delegator, productStoreId, locale, defaultCurrencyUomId); - - // set the external id with the eBay Item Id + + // set the external id with the eBay Item Id String externalId = (String) parameters.get("externalId"); - + // set the transaction id with the eBay Transacation Id String transactionId = (String) parameters.get("transactionId"); - + if (UtilValidate.isNotEmpty(externalId)) { if (externalOrderExists(delegator, externalId, transactionId) != null && create) { - return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.externalIdAlreadyExist", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.externalIdAlreadyExist", locale)); } cart.setExternalId(externalId); cart.setTransactionId(transactionId); } else { return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.externalIdNotAvailable", locale)); } - + cart.setOrderType("SALES_ORDER"); cart.setChannelType("EBAY_SALES_CHANNEL"); cart.setUserLogin(userLogin, dispatcher); cart.setProductStoreId(productStoreId); - + if (UtilValidate.isNotEmpty(facilityId)) { cart.setFacilityId(facilityId); } - + String amountStr = (String) parameters.get("amountPaid"); BigDecimal amountPaid = BigDecimal.ZERO; - + if (UtilValidate.isNotEmpty(amountStr)) { amountPaid = new BigDecimal(amountStr); - } - + } + // add the payment EXT_BAY for the paid amount cart.addPaymentAmount("EXT_EBAY", amountPaid, externalId, null, true, false, false); - + // set the order date with the eBay created date Timestamp orderDate = UtilDateTime.nowTimestamp(); if (UtilValidate.isNotEmpty((String) parameters.get("createdDate"))) { @@ -758,7 +758,7 @@ orderDate = new Timestamp(createdDate.getTime()); } cart.setOrderDate(orderDate); - + // check if the producId exists and it is valid String productId = (String) parameters.get("productId"); if (UtilValidate.isEmpty(productId)) { @@ -769,46 +769,46 @@ return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.productIdDoesNotExist", locale)); } } - + // Before import the order from eBay to OFBiz is mandatory that the payment has be received String paidTime = (String) parameters.get("paidTime"); if (UtilValidate.isEmpty(paidTime)) { return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ordersImportFromEbay.paymentIsStillNotReceived", locale)); - } - + } + BigDecimal unitPrice = new BigDecimal((String) parameters.get("transactionPrice")); BigDecimal quantity = new BigDecimal((String) parameters.get("quantityPurchased")); cart.addItemToEnd(productId, null, quantity, unitPrice, null, null, null, "PRODUCT_ORDER_ITEM", dispatcher, Boolean.FALSE, Boolean.FALSE); - + // set partyId from if (UtilValidate.isNotEmpty(payToPartyId)) { cart.setBillFromVendorPartyId(payToPartyId); } - + // Apply shipping costs as order adjustment String shippingCost = (String) parameters.get("shippingServiceCost"); if (UtilValidate.isNotEmpty(shippingCost)) { double shippingAmount = new Double(shippingCost).doubleValue(); if (shippingAmount > 0) { - GenericValue shippingAdjustment = makeOrderAdjustment(delegator, "SHIPPING_CHARGES", cart.getOrderId(), null, null, shippingAmount, 0.0); + GenericValue shippingAdjustment = makeOrderAdjustment(delegator, "SHIPPING_CHARGES", cart.getOrderId(), null, null, shippingAmount, 0.0); if (shippingAdjustment != null) { cart.addAdjustment(shippingAdjustment); } } } - + // Apply additional shipping costs as order adjustment String shippingTotalAdditionalCost = (String) parameters.get("shippingTotalAdditionalCost"); if (UtilValidate.isNotEmpty(shippingTotalAdditionalCost)) { double shippingAdditionalCost = new Double(shippingTotalAdditionalCost).doubleValue(); if (shippingAdditionalCost > 0) { - GenericValue shippingAdjustment = makeOrderAdjustment(delegator, "MISCELLANEOUS_CHARGE", cart.getOrderId(), null, null, shippingAdditionalCost, 0.0); + GenericValue shippingAdjustment = makeOrderAdjustment(delegator, "MISCELLANEOUS_CHARGE", cart.getOrderId(), null, null, shippingAdditionalCost, 0.0); if (shippingAdjustment != null) { cart.addAdjustment(shippingAdjustment); } } } - + // Apply sales tax as order adjustment String salesTaxAmount = (String) parameters.get("salesTaxAmount"); String salesTaxPercent = (String) parameters.get("salesTaxPercent"); @@ -825,7 +825,7 @@ } } } - + // order has to be created ? if (create) { Debug.logInfo("Importing new order from eBay", module); @@ -844,7 +844,7 @@ partyId = (String) partyAttribute.get("partyId"); Debug.logInfo("Found existing party associated to the eBay buyer: " + partyId, module); GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId)); - + contactMechId = setShippingAddressContactMech(dispatcher, delegator, party, userLogin, parameters); String emailBuyer = (String) parameters.get("emailBuyer"); if (!(emailBuyer.equals("") || emailBuyer.equalsIgnoreCase("Invalid Request"))) { @@ -852,17 +852,17 @@ } String phoneContactMech = setPhoneContactMech(dispatcher, delegator, party, userLogin, parameters); } - + // create party if none exists already if (UtilValidate.isEmpty(partyId)) { Debug.logInfo("Creating new party for the eBay buyer.", module); - partyId = createCustomerParty(dispatcher, (String) parameters.get("buyerName"), userLogin); + partyId = createCustomerParty(dispatcher, (String) parameters.get("buyerName"), userLogin); if (UtilValidate.isEmpty(partyId)) { Debug.logWarning("Using admin party for the eBay buyer.", module); partyId = "admin"; - } - } - + } + } + // create new party's contact information if (UtilValidate.isEmpty(contactMechId)) { Debug.logInfo("Creating new postal address for party: " + partyId, module); @@ -879,22 +879,22 @@ if (UtilValidate.isNotEmpty(emailBuyer) && !emailBuyer.equalsIgnoreCase("Invalid Request")) { Debug.logInfo("Creating new email for party: " + partyId, module); createPartyEmail(dispatcher, partyId, emailBuyer, userLogin); - } - } + } + } Debug.logInfo("Setting cart roles for party: " + partyId, module); cart.setBillToCustomerPartyId(partyId); cart.setPlacingCustomerPartyId(partyId); cart.setShipToCustomerPartyId(partyId); cart.setEndUserCustomerPartyId(partyId); - + Debug.logInfo("Setting contact mech in cart: " + contactMechId, module); cart.setShippingContactMechId(contactMechId); cart.setMaySplit(Boolean.FALSE); - + Debug.logInfo("Setting shipment method: " + (String) parameters.get("shippingService"), module); setShipmentMethodType(cart, (String) parameters.get("shippingService")); - + cart.makeAllShipGroupInfos(); // create the order @@ -902,16 +902,16 @@ CheckOutHelper checkout = new CheckOutHelper(dispatcher, delegator, cart); Debug.logInfo("Creating order.", module); Map orderCreate = checkout.createOrder(userLogin); - + String orderId = (String)orderCreate.get("orderId"); Debug.logInfo("Created order with id: " + orderId, module); - + // approve the order if (UtilValidate.isNotEmpty(orderId)) { Debug.logInfo("Approving order with id: " + orderId, module); boolean approved = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId); Debug.logInfo("Order approved with result: " + approved, module); - + // create the payment from the preference if (approved) { Debug.logInfo("Creating payment for approved order.", module); @@ -926,14 +926,14 @@ } return ServiceUtil.returnSuccess(); } - - private static boolean createPaymentFromPaymentPreferences(GenericDelegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, + + private static boolean createPaymentFromPaymentPreferences(GenericDelegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, String externalId, Timestamp orderDate, String partyIdFrom) { List paymentPreferences = null; try { Map paymentFields = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_RECEIVED", "paymentMethodTypeId", "EXT_EBAY"); paymentPreferences = delegator.findByAnd("OrderPaymentPreference", paymentFields); - + if (UtilValidate.isNotEmpty(paymentPreferences)) { Iterator i = paymentPreferences.iterator(); while (i.hasNext()) { @@ -948,13 +948,13 @@ return false; } return true; - } - - private static boolean createPayment(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, + } + + private static boolean createPayment(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, String orderId, String externalId, Timestamp orderDate, String partyIdFrom) { try { GenericDelegator delegator = paymentPreference.getDelegator(); - + // create the PaymentGatewayResponse String responseId = delegator.getNextSeqId("PaymentGatewayResponse"); GenericValue response = delegator.makeValue("PaymentGatewayResponse"); @@ -967,38 +967,38 @@ response.set("referenceNum", externalId); response.set("transactionDate", orderDate); delegator.createOrStore(response); - + // create the payment - Map results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, - "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), + Map results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, + "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "paymentFromId", partyIdFrom, "paymentRefNum", externalId, "comments", "Payment receive via eBay")); - + if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) { - Debug.logError((String) results.get(ModelService.ERROR_MESSAGE), module); + Debug.logError((String) results.get(ModelService.ERROR_MESSAGE), module); return false; } - return true; + return true; } catch (Exception e) { Debug.logError(e, "Failed to create the payment for order " + orderId, module); return false; } } - - private static GenericValue makeOrderAdjustment(GenericDelegator delegator, String orderAdjustmentTypeId, String orderId, + + private static GenericValue makeOrderAdjustment(GenericDelegator delegator, String orderAdjustmentTypeId, String orderId, String orderItemSeqId, String shipGroupSeqId, double amount, double sourcePercentage) { GenericValue orderAdjustment = null; - + try { if (UtilValidate.isNotEmpty(orderItemSeqId)) { orderItemSeqId = "_NA_"; } if (UtilValidate.isNotEmpty(shipGroupSeqId)) { - shipGroupSeqId = "_NA_"; + shipGroupSeqId = "_NA_"; } - - Map inputMap = UtilMisc.toMap("orderAdjustmentTypeId", orderAdjustmentTypeId, "orderId", orderId, "orderItemSeqId", orderItemSeqId, + + Map inputMap = UtilMisc.toMap("orderAdjustmentTypeId", orderAdjustmentTypeId, "orderId", orderId, "orderItemSeqId", orderItemSeqId, "shipGroupSeqId", shipGroupSeqId, "amount", new Double(amount)); if (sourcePercentage != 0) { inputMap.put("sourcePercentage", new Double(sourcePercentage)); @@ -1012,26 +1012,26 @@ private static String createCustomerParty(LocalDispatcher dispatcher, String name, GenericValue userLogin) { String partyId = null; - + try { if (UtilValidate.isNotEmpty(name) && UtilValidate.isNotEmpty(userLogin)) { Debug.logVerbose("Creating Customer Party: "+name, module); - + // Try to split the lastname from the firstname String firstName = ""; String lastName = ""; int pos = name.indexOf(" "); - + if (pos >= 0) { firstName = name.substring(0, pos); lastName = name.substring(pos+1); } else { - lastName = name; + lastName = name; } - - Map summaryResult = dispatcher.runSync("createPerson", UtilMisc.<String, Object>toMap("description", name, "firstName", firstName, "lastName", lastName, - "userLogin", userLogin, "comments", "Created via eBay")); - partyId = (String) summaryResult.get("partyId"); + + Map summaryResult = dispatcher.runSync("createPerson", UtilMisc.<String, Object>toMap("description", name, "firstName", firstName, "lastName", lastName, + "userLogin", userLogin, "comments", "Created via eBay")); + partyId = (String) summaryResult.get("partyId"); Debug.logVerbose("Created Customer Party: "+partyId, module); } } catch (Exception e) { @@ -1039,8 +1039,8 @@ } return partyId; } - - private static String createAddress(LocalDispatcher dispatcher, String partyId, GenericValue userLogin, + + private static String createAddress(LocalDispatcher dispatcher, String partyId, GenericValue userLogin, String contactMechPurposeTypeId, Map address) { Debug.logInfo("Creating postal address with input map: " + address, module); String contactMechId = null; @@ -1051,8 +1051,8 @@ context.put("address2", (String)address.get("shippingAddressStreet2")); context.put("postalCode", (String)address.get("shippingAddressPostalCode")); context.put("userLogin", userLogin); - context.put("contactMechPurposeTypeId", contactMechPurposeTypeId); - + context.put("contactMechPurposeTypeId", contactMechPurposeTypeId); + String country = (String)address.get("shippingAddressCountry"); String state = (String)address.get("shippingAddressStateOrProvince"); String city = (String)address.get("shippingAddressCityName"); @@ -1065,9 +1065,9 @@ } return contactMechId; } - + private static void correctCityStateCountry(LocalDispatcher dispatcher, Map map, String city, String state, String country) { - try { + try { Debug.logInfo("correctCityStateCountry params: " + city + ", " + state + ", " + country, module); if (UtilValidate.isEmpty(country)) { country = "US"; @@ -1097,52 +1097,52 @@ Debug.logError(e, "Failed to correctCityStateCountry", module); } } - + private static String createPartyPhone(LocalDispatcher dispatcher, String partyId, String phoneNumber, GenericValue userLogin) { Map summaryResult = FastMap.newInstance(); Map context = FastMap.newInstance(); String phoneContactMechId = null; - - try { - context.put("contactNumber", phoneNumber); + + try { + context.put("contactNumber", phoneNumber); context.put("partyId", partyId); context.put("userLogin", userLogin); - context.put("contactMechPurposeTypeId", "PHONE_SHIPPING"); + context.put("contactMechPurposeTypeId", "PHONE_SHIPPING"); summaryResult = dispatcher.runSync("createPartyTelecomNumber", context); phoneContactMechId = (String)summaryResult.get("contactMechId"); - } catch (Exception e) { + } catch (Exception e) { Debug.logError(e, "Failed to createPartyPhone", module); } return phoneContactMechId; } - + private static String createPartyEmail(LocalDispatcher dispatcher, String partyId, String email, GenericValue userLogin) { Map context = FastMap.newInstance(); Map summaryResult = FastMap.newInstance(); String emailContactMechId = null; - + try { if (UtilValidate.isNotEmpty(email)) { context.clear(); context.put("emailAddress", email); context.put("userLogin", userLogin); - context.put("contactMechTypeId", "EMAIL_ADDRESS"); + context.put("contactMechTypeId", "EMAIL_ADDRESS"); summaryResult = dispatcher.runSync("createEmailAddress", context); emailContactMechId = (String) summaryResult.get("contactMechId"); - + context.clear(); context.put("partyId", partyId); context.put("contactMechId", emailContactMechId); - context.put("contactMechPurposeTypeId", "OTHER_EMAIL"); - context.put("userLogin", userLogin); + context.put("contactMechPurposeTypeId", "OTHER_EMAIL"); + context.put("userLogin", userLogin); summaryResult = dispatcher.runSync("createPartyContactMech", context); } - } catch (Exception e) { + } catch (Exception e) { Debug.logError(e, "Failed to createPartyEmail", module); } return emailContactMechId; } - + public static void createEbayCustomer(LocalDispatcher dispatcher, String partyId, String ebayUserIdBuyer, String eias, GenericValue userLogin) { Map context = FastMap.newInstance(); Map summaryResult = FastMap.newInstance(); @@ -1154,7 +1154,7 @@ context.put("userLogin", userLogin); summaryResult = dispatcher.runSync("createPartyAttribute", context); } catch (Exception e) { - Debug.logError(e, "Failed to create eBay EIAS party attribute"); + Debug.logError(e, "Failed to create eBay EIAS party attribute"); } context.clear(); summaryResult.clear(); @@ -1167,7 +1167,7 @@ context.put("userLogin", userLogin); summaryResult = dispatcher.runSync("createPartyAttribute", context); } catch (Exception e) { - Debug.logError(e, "Failed to create eBay userId party attribute"); + Debug.logError(e, "Failed to create eBay userId party attribute"); } } } @@ -1176,7 +1176,7 @@ GenericValue geo = null; try { Debug.logInfo("geocode: " + geoCode, module); - + geo = EntityUtil.getFirst(delegator.findByAnd("Geo", UtilMisc.toMap("geoCode", geoCode.toUpperCase(), "geoTypeId", "COUNTRY"))); Debug.logInfo("Found a geo entity " + geo, module); if (UtilValidate.isEmpty(geo)) { @@ -1194,12 +1194,12 @@ Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } - + Map result = ServiceUtil.returnSuccess(); result.put("geoId", (String)geo.get("geoId")); return result; } - + private static GenericValue externalOrderExists(GenericDelegator delegator, String externalId, String transactionId) throws GenericEntityException { Debug.logInfo("Checking for existing externalId: " + externalId +" and transactionId: " + transactionId, module); GenericValue orderHeader = null; @@ -1208,8 +1208,8 @@ orderHeader = EntityUtil.getFirst(entities); } return orderHeader; - } - + } + private static String convertDate(String dateIn, String fromDateFormat, String toDateFormat) { String dateOut; try { @@ -1222,15 +1222,15 @@ } return dateOut; } - + private static void setShipmentMethodType(ShoppingCart cart, String shippingService) { String partyId = "_NA_"; String shipmentMethodTypeId = "NO_SHIPPING"; - + if (shippingService != null) { if ("USPSPriority".equals(shippingService)) { partyId = "USPS"; - shipmentMethodTypeId = "PRIORITY"; + shipmentMethodTypeId = "PRIORITY"; } else if ("UPSGround".equals(shippingService)) { partyId = "UPS"; shipmentMethodTypeId = "GROUND"; @@ -1261,36 +1261,36 @@ } else if ("LocalDelivery".equals(shippingService)) { partyId = "_NA_"; shipmentMethodTypeId = "PICK_UP"; - } + } } - + cart.setCarrierPartyId(partyId); - cart.setShipmentMethodTypeId(shipmentMethodTypeId); - } - + cart.setShipmentMethodTypeId(shipmentMethodTypeId); + } + private static String setShippingAddressContactMech (LocalDispatcher dispatcher, GenericDelegator delegator, GenericValue party, GenericValue userLogin, Map parameters) { String contactMechId = null; String partyId = (String) party.get("partyId"); - + // find all contact mechs for this party with a shipping location purpose. Collection shippingLocations = ContactHelper.getContactMechByPurpose(party, "SHIPPING_LOCATION", false); - + // check them to see if one matches Iterator shippingLocationsIterator = shippingLocations.iterator(); while (shippingLocationsIterator.hasNext()) { GenericValue shippingLocation = (GenericValue) shippingLocationsIterator.next(); contactMechId = shippingLocation.getString("contactMechId"); GenericValue postalAddress; - try { + try { // get the postal address for this contact mech postalAddress = delegator.findByPrimaryKey("PostalAddress", UtilMisc.toMap("contactMechId", contactMechId)); - + // match values to compare by modifying them the same way they were when they were created String country = ((String)parameters.get("shippingAddressCountry")).toUpperCase(); String state = ((String)parameters.get("shippingAddressStateOrProvince")).toUpperCase(); String city = (String)parameters.get("shippingAddressCityName"); correctCityStateCountry(dispatcher, parameters, city, state, country); - + // TODO: The following comparison does not consider the To Name or Attn: lines of the address. // // now compare values. If all fields match, that's our shipping address. Return the related contact mech id. @@ -1301,24 +1301,24 @@ parameters.get("countryGeoId").toString().equals((postalAddress.get("countryGeoId").toString())) && parameters.get("shippingAddressPostalCode").toString().equals((postalAddress.get("postalCode").toString())) ) { // this is an exact address match!! - return contactMechId; - } + return contactMechId; + } } catch (Exception e) { - Debug.logError(e, "Problem with verifying postal addresses for contactMechId " + contactMechId + ".", module); + Debug.logError(e, "Problem with verifying postal addresses for contactMechId " + contactMechId + ".", module); } - } + } // none of the existing contact mechs/postal addresses match (or none were found). Create a new one and return the related contact mech id. Debug.logInfo("Unable to find matching postal address for partyId " + partyId + ". Creating a new one.", module); return createAddress(dispatcher, partyId, userLogin, "SHIPPING_LOCATION", parameters); } - + private static String setEmailContactMech (LocalDispatcher dispatcher, GenericDelegator delegator, GenericValue party, GenericValue userLogin, Map parameters) { String contactMechId = null; String partyId = (String) party.get("partyId"); - - // find all contact mechs for this party with a email address purpose. + + // find all contact mechs for this party with a email address purpose. Collection emailAddressContactMechs = ContactHelper.getContactMechByPurpose(party, "OTHER_EMAIL", false); - + // check them to see if one matches Iterator emailAddressesContactMechsIterator = emailAddressContactMechs.iterator(); while (emailAddressesContactMechsIterator.hasNext()) { @@ -1326,43 +1326,43 @@ contactMechId = emailAddressContactMech.getString("contactMechId"); // now compare values. If one matches, that's our email address. Return the related contact mech id. if (parameters.get("emailBuyer").toString().equals((emailAddressContactMech.get("infoString").toString()))) { - return contactMechId; + return contactMechId; } - } + } // none of the existing contact mechs/email addresses match (or none were found). Create a new one and return the related contact mech id. Debug.logInfo("Unable to find matching postal address for partyId " + partyId + ". Creating a new one.", module); return createPartyEmail(dispatcher, partyId, (String) parameters.get("emailBuyer"), userLogin); } - + private static String setPhoneContactMech (LocalDispatcher dispatcher, GenericDelegator delegator, GenericValue party, GenericValue userLogin, Map parameters) { String contactMechId = null; String partyId = (String) party.get("partyId"); - + // find all contact mechs for this party with a telecom number purpose. Collection phoneNumbers = ContactHelper.getContactMechByPurpose(party, "PHONE_SHIPPING", false); - + // check them to see if one matches Iterator phoneNumbersIterator = phoneNumbers.iterator(); while (phoneNumbersIterator.hasNext()) { GenericValue phoneNumberContactMech = (GenericValue) phoneNumbersIterator.next(); contactMechId = phoneNumberContactMech.getString("contactMechId"); GenericValue phoneNumber; - try { + try { // get the phone number for this contact mech phoneNumber = delegator.findByPrimaryKey("TelecomNumber", UtilMisc.toMap("contactMechId", contactMechId)); - + // now compare values. If one matches, that's our phone number. Return the related contact mech id. - if (parameters.get("shippingAddressPhone").toString().equals((phoneNumber.get("contactNumber").toString()))) { - return contactMechId; + if (parameters.get("shippingAddressPhone").toString().equals((phoneNumber.get("contactNumber").toString()))) { + return contactMechId; } } catch (Exception e) { Debug.logError("Problem with verifying phone number for contactMechId " + contactMechId + ".", module); } - } + } // none of the existing contact mechs/email addresses match (or none were found). Create a new one and return the related contact mech id. Debug.logInfo("Unable to find matching postal address for partyId " + partyId + ". Creating a new one.", module); return createPartyPhone(dispatcher, partyId, (String) parameters.get("shippingAddressPhone"), userLogin); - } + } private static String retrieveProductIdFromTitle(GenericDelegator delegator, String title) { String productId = ""; Modified: ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ProductsExportToEbay.java URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ProductsExportToEbay.java?rev=757101&r1=757100&r2=757101&view=diff ============================================================================== --- ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ProductsExportToEbay.java (original) +++ ofbiz/trunk/specialpurpose/ebay/src/org/ofbiz/ebay/ProductsExportToEbay.java Sat Mar 21 23:47:53 2009 @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -50,64 +50,64 @@ import org.w3c.dom.Element; public class ProductsExportToEbay { - + private static final String resource = "EbayUiLabels"; private static final String module = ProductsExportToEbay.class.getName(); - + public static Map exportToEbay(DispatchContext dctx, Map context) { Locale locale = (Locale) context.get("locale"); try { String configString = "ebayExport.properties"; - + // get the Developer Key String devID = UtilProperties.getPropertyValue(configString, "eBayExport.devID"); - + // get the Application Key String appID = UtilProperties.getPropertyValue(configString, "eBayExport.appID"); - + // get the Certifcate Key String certID = UtilProperties.getPropertyValue(configString, "eBayExport.certID"); - + // get the Token String token = UtilProperties.getPropertyValue(configString, "eBayExport.token"); - + // get the Compatibility Level String compatibilityLevel = UtilProperties.getPropertyValue(configString, "eBayExport.compatibilityLevel"); - + // get the Site ID String siteID = UtilProperties.getPropertyValue(configString, "eBayExport.siteID"); - + // get the xmlGatewayUri String xmlGatewayUri = UtilProperties.getPropertyValue(configString, "eBayExport.xmlGatewayUri"); - + StringBuffer dataItemsXml = new StringBuffer(); - + /* String itemId = ""; - if (!ServiceUtil.isFailure(buildAddTransactionConfirmationItemRequest(context, dataItemsXml, token, itemId))) { + if (!ServiceUtil.isFailure(buildAddTransactionConfirmationItemRequest(context, dataItemsXml, token, itemId))) { Map result = postItem(xmlGatewayUri, dataItemsXml, devID, appID, certID, "AddTransactionConfirmationItem"); Debug.logInfo(result.toString(), module); } */ - - if (!ServiceUtil.isFailure(buildDataItemsXml(dctx, context, dataItemsXml, token))) { + + if (!ServiceUtil.isFailure(buildDataItemsXml(dctx, context, dataItemsXml, token))) { Map result = postItem(xmlGatewayUri, dataItemsXml, devID, appID, certID, "AddItem", compatibilityLevel, siteID); - if (ServiceUtil.isFailure(result)) { + if (ServiceUtil.isFailure(result)) { return ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(result)); - } + } } - } catch (Exception e) { + } catch (Exception e) { Debug.logError("Exception in exportToEbay " + e, module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "productsExportToEbay.exceptionInExportToEbay", locale)); } return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "productsExportToEbay.productItemsSentCorrecltyToEbay", locale)); } - + private static void appendRequesterCredentials(Element elem, Document doc, String token) { Element requesterCredentialsElem = UtilXml.addChildElement(elem, "RequesterCredentials", doc); UtilXml.addChildElementValue(requesterCredentialsElem, "eBayAuthToken", token, doc); } - + private static String toString(InputStream inputStream) throws IOException { String string; StringBuilder outputBuilder = new StringBuilder(); @@ -119,13 +119,13 @@ } return outputBuilder.toString(); } - - private static Map postItem(String postItemsUrl, StringBuffer dataItems, String devID, String appID, String certID, + + private static Map postItem(String postItemsUrl, StringBuffer dataItems, String devID, String appID, String certID, String callName, String compatibilityLevel, String siteID) throws IOException { if (Debug.verboseOn()) { Debug.logVerbose("Request of " + callName + " To eBay:\n" + dataItems.toString(), module); } - + HttpURLConnection connection = (HttpURLConnection)(new URL(postItemsUrl)).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); @@ -137,16 +137,16 @@ connection.setRequestProperty("X-EBAY-API-CALL-NAME", callName); connection.setRequestProperty("X-EBAY-API-SITEID", siteID); connection.setRequestProperty("Content-Type", "text/xml"); - + OutputStream outputStream = connection.getOutputStream(); outputStream.write(dataItems.toString().getBytes()); outputStream.close(); - + int responseCode = connection.getResponseCode(); InputStream inputStream; Map result = FastMap.newInstance(); String response = null; - + if (responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); @@ -157,30 +157,30 @@ response = toString(inputStream); result = ServiceUtil.returnFailure(response); } - + if (Debug.verboseOn()) { Debug.logVerbose("Response of " + callName + " From eBay:\n" + response, module); } - + return result; } - + private static Map buildDataItemsXml(DispatchContext dctx, Map context, StringBuffer dataItemsXml, String token) { Locale locale = (Locale)context.get("locale"); try { GenericDelegator delegator = dctx.getDelegator(); List selectResult = (List)context.get("selectResult"); - + // Get the list of products to be exported to eBay List productsList = delegator.findList("Product", EntityCondition.makeCondition("productId", EntityOperator.IN, selectResult), null, null, null, false); - + try { Document itemDocument = UtilXml.makeEmptyXmlDocument("AddItemRequest"); Element itemRequestElem = itemDocument.getDocumentElement(); itemRequestElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); - + appendRequesterCredentials(itemRequestElem, itemDocument, token); - + // Iterate the product list getting all the relevant data Iterator productsListItr = productsList.iterator(); while (productsListItr.hasNext()) { @@ -188,7 +188,7 @@ String title = parseText(prod.getString("internalName")); String description = parseText(prod.getString("internalName")); String qnt = (String)context.get("qnt"); - + Element itemElem = UtilXml.addChildElement(itemRequestElem, "Item", itemDocument); UtilXml.addChildElementValue(itemElem, "Country", (String)context.get("country"), itemDocument); UtilXml.addChildElementValue(itemElem, "Location", (String)context.get("location"), itemDocument); @@ -199,31 +199,31 @@ UtilXml.addChildElementValue(itemElem, "ListingDuration", (String)context.get("listingDuration"), itemDocument); UtilXml.addChildElementValue(itemElem, "Quantity", qnt, itemDocument); UtilXml.addChildElementValue(itemElem, "UseTaxTable", "true", itemDocument); - + setPaymentMethodAccepted(itemDocument, itemElem, context); - + String categoryCode = (String)context.get("ebayCategory"); String categoryParent = ""; String levelLimit = ""; - - if (categoryCode != null) { + + if (categoryCode != null) { String[] params = categoryCode.split("_"); - - if (params == null || params.length != 3) { + + if (params == null || params.length != 3) { ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "productsExportToEbay.parametersNotCorrectInGetEbayCategories", locale)); - } else { + } else { categoryParent = params[1]; levelLimit = params[2]; } } - + Element primaryCatElem = UtilXml.addChildElement(itemElem, "PrimaryCategory", itemDocument); UtilXml.addChildElementValue(primaryCatElem, "CategoryID", categoryParent, itemDocument); - + Element startPriceElem = UtilXml.addChildElementValue(itemElem, "StartPrice", (String)context.get("startPrice"), itemDocument); startPriceElem.setAttribute("currencyID", "USD"); } - + dataItemsXml.append(UtilXml.writeXmlDocument(itemDocument)); } catch (Exception e) { Debug.logError("Exception during building data items to eBay", module); @@ -232,33 +232,33 @@ } catch (Exception e) { Debug.logError("Exception during building data items to eBay", module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "productsExportToEbay.exceptionDuringBuildingDataItemsToEbay", locale)); - } + } return ServiceUtil.returnSuccess(); } - + private static Map buildCategoriesXml(Map context, StringBuffer dataItemsXml, String token, String siteID, String categoryParent, String levelLimit) { Locale locale = (Locale)context.get("locale"); try { Document itemRequest = UtilXml.makeEmptyXmlDocument("GetCategoriesRequest"); Element itemRequestElem = itemRequest.getDocumentElement(); itemRequestElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); - + appendRequesterCredentials(itemRequestElem, itemRequest, token); - + UtilXml.addChildElementValue(itemRequestElem, "DetailLevel", "ReturnAll", itemRequest); UtilXml.addChildElementValue(itemRequestElem, "CategorySiteID", siteID, itemRequest); - + if (UtilValidate.isNotEmpty(categoryParent)) { UtilXml.addChildElementValue(itemRequestElem, "CategoryParent", categoryParent, itemRequest); } - + if (UtilValidate.isEmpty(levelLimit)) { levelLimit = "1"; } - + UtilXml.addChildElementValue(itemRequestElem, "LevelLimit", levelLimit, itemRequest); UtilXml.addChildElementValue(itemRequestElem, "ViewAllNodes", "true", itemRequest); - + dataItemsXml.append(UtilXml.writeXmlDocument(itemRequest)); } catch (Exception e) { Debug.logError("Exception during building data items to eBay", module); @@ -266,23 +266,23 @@ } return ServiceUtil.returnSuccess(); } - + private static Map buildSetTaxTableRequestXml(DispatchContext dctx, Map context, StringBuffer setTaxTableRequestXml, String token) { Locale locale = (Locale)context.get("locale"); try { Document taxRequestDocument = UtilXml.makeEmptyXmlDocument("SetTaxTableRequest"); Element taxRequestElem = taxRequestDocument.getDocumentElement(); taxRequestElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); - + appendRequesterCredentials(taxRequestElem, taxRequestDocument, token); - + Element taxTableElem = UtilXml.addChildElement(taxRequestElem, "TaxTable", taxRequestDocument); Element taxJurisdictionElem = UtilXml.addChildElement(taxTableElem, "TaxJurisdiction", taxRequestDocument); - + UtilXml.addChildElementValue(taxJurisdictionElem, "JurisdictionID", "NY", taxRequestDocument); UtilXml.addChildElementValue(taxJurisdictionElem, "SalesTaxPercent", "4.25", taxRequestDocument); UtilXml.addChildElementValue(taxJurisdictionElem, "ShippingIncludedInTax", "false", taxRequestDocument); - + setTaxTableRequestXml.append(UtilXml.writeXmlDocument(taxRequestDocument)); } catch (Exception e) { Debug.logError("Exception during building request set tax table to eBay", module); @@ -290,23 +290,23 @@ } return ServiceUtil.returnSuccess(); } - + private static Map buildAddTransactionConfirmationItemRequest(Map context, StringBuffer dataItemsXml, String token, String itemId) { Locale locale = (Locale)context.get("locale"); try { Document transDoc = UtilXml.makeEmptyXmlDocument("AddTransactionConfirmationItemRequest"); Element transElem = transDoc.getDocumentElement(); transElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); - + appendRequesterCredentials(transElem, transDoc, token); - + UtilXml.addChildElementValue(transElem, "ItemID", itemId, transDoc); UtilXml.addChildElementValue(transElem, "ListingDuration", "Days_1", transDoc); Element negotiatePriceElem = UtilXml.addChildElementValue(transElem, "NegotiatedPrice", "50.00", transDoc); negotiatePriceElem.setAttribute("currencyID", "USD"); UtilXml.addChildElementValue(transElem, "RecipientRelationType", "1", transDoc); UtilXml.addChildElementValue(transElem, "RecipientUserID", "buyer_anytime", transDoc); - + dataItemsXml.append(UtilXml.writeXmlDocument(transDoc)); Debug.logInfo(dataItemsXml.toString(), module); } catch (Exception e) { @@ -315,7 +315,7 @@ } return ServiceUtil.returnSuccess(); } - + private static void setPaymentMethodAccepted(Document itemDocument, Element itemElem, Map context) { String payPal = (String)context.get("paymentPayPal"); String visaMC = (String)context.get("paymentVisaMC"); @@ -329,7 +329,7 @@ String mocc = (String)context.get("paymentMOCC"); String moneyXferAccepted = (String)context.get("paymentMoneyXferAccepted"); String personalCheck = (String)context.get("paymentPersonalCheck"); - + // PayPal if (UtilValidate.isNotEmpty(payPal) && "on".equals(payPal)) { UtilXml.addChildElementValue(itemElem, "PaymentMethods", "PayPal", itemDocument); @@ -380,70 +380,70 @@ UtilXml.addChildElementValue(itemElem, "PaymentMethods", "PersonalCheck", itemDocument); } } - + public static Map getEbayCategories(DispatchContext dctx, Map context) { Locale locale = (Locale) context.get("locale"); String categoryCode = (String)context.get("categoryCode"); Map result = null; - + try { String configString = "ebayExport.properties"; - + // get the Developer Key String devID = UtilProperties.getPropertyValue(configString, "eBayExport.devID"); - + // get the Application Key String appID = UtilProperties.getPropertyValue(configString, "eBayExport.appID"); - + // get the Certifcate Key String certID = UtilProperties.getPropertyValue(configString, "eBayExport.certID"); - + // get the Token String token = UtilProperties.getPropertyValue(configString, "eBayExport.token"); - + // get the Compatibility Level String compatibilityLevel = UtilProperties.getPropertyValue(configString, "eBayExport.compatibilityLevel"); - + // get the Site ID String siteID = UtilProperties.getPropertyValue(configString, "eBayExport.siteID"); - + // get the xmlGatewayUri String xmlGatewayUri = UtilProperties.getPropertyValue(configString, "eBayExport.xmlGatewayUri"); - + String categoryParent = ""; String levelLimit = ""; - - if (categoryCode != null) { + + if (categoryCode != null) { String[] params = categoryCode.split("_"); - - if (params == null || params.length != 3) { + + if (params == null || params.length != 3) { ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "productsExportToEbay.parametersNotCorrectInGetEbayCategories", locale)); - } else { + } else { categoryParent = params[1]; levelLimit = params[2]; Integer level = new Integer(levelLimit); levelLimit = (level.intValue() + 1) + ""; } } - + StringBuffer dataItemsXml = new StringBuffer(); - - if (!ServiceUtil.isFailure(buildCategoriesXml(context, dataItemsXml, token, siteID, categoryParent, levelLimit))) { + + if (!ServiceUtil.isFailure(buildCategoriesXml(context, dataItemsXml, token, siteID, categoryParent, levelLimit))) { Map resultCat = postItem(xmlGatewayUri, dataItemsXml, devID, appID, certID, "GetCategories", compatibilityLevel, siteID); String successMessage = (String)resultCat.get("successMessage"); - if (successMessage != null) { + if (successMessage != null) { result = readEbayCategoriesResponse(successMessage, locale); } else { ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(resultCat)); - } + } } - } catch (Exception e) { + } catch (Exception e) { Debug.logError("Exception in GetEbayCategories " + e, module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "productsExportToEbay.exceptionInGetEbayCategories", locale)); } return result; } - + private static Map readEbayCategoriesResponse(String msg, Locale locale) { Map results = null; List categories = FastList.newInstance(); @@ -461,36 +461,36 @@ } return ServiceUtil.returnFailure(errorMessage); } else { - // retrieve Category Array + // retrieve Category Array List categoryArray = UtilXml.childElementList(elemResponse, "CategoryArray"); Iterator categoryArrayElemIter = categoryArray.iterator(); while (categoryArrayElemIter.hasNext()) { Element categoryArrayElement = (Element)categoryArrayElemIter.next(); - + // retrieve Category List category = UtilXml.childElementList(categoryArrayElement, "Category"); Iterator categoryElemIter = category.iterator(); while (categoryElemIter.hasNext()) { Map categ = FastMap.newInstance(); - Element categoryElement = (Element)categoryElemIter.next(); - + Element categoryElement = (Element)categoryElemIter.next(); + String categoryCode = ("true".equalsIgnoreCase((UtilXml.childElementValue(categoryElement, "LeafCategory", "").trim())) ? "Y" : "N") + "_" + - UtilXml.childElementValue(categoryElement, "CategoryID", "").trim() + "_" + + UtilXml.childElementValue(categoryElement, "CategoryID", "").trim() + "_" + UtilXml.childElementValue(categoryElement, "CategoryLevel", "").trim(); categ.put("CategoryCode", categoryCode); categ.put("CategoryName", UtilXml.childElementValue(categoryElement, "CategoryName")); categories.add(categ); - } + } } categories = UtilMisc.sortMaps(categories, UtilMisc.toList("CategoryName")); results = UtilMisc.toMap("categories", categories); - } + } } catch (Exception e) { return ServiceUtil.returnFailure(); } return results; } - + private static String parseText(String text) { Pattern htmlPattern = Pattern.compile("[<](.+?)[>]"); Pattern tabPattern = Pattern.compile("\\s"); |
Free forum by Nabble | Edit this page |