Search in sources :

Example 1 with ModuleConfig

use of com.salesmanager.core.model.system.ModuleConfig in project shopizer by shopizer-ecommerce.

the class USPSParsedElements method getShippingQuotes.

@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote shippingQuote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration configuration, IntegrationModule module, ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {
    if (packages == null) {
        return null;
    }
    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }
    // only applies to Canada and US
    /*		Country country = delivery.getCountry();
		if(!country.getIsoCode().equals("US") || !country.getIsoCode().equals("US")){
			throw new IntegrationException("USPS Not configured for shipping in country " + country.getIsoCode());
		}*/
    // supports en and fr
    String language = locale.getLanguage();
    if (!language.equals(Locale.FRENCH.getLanguage()) && !language.equals(Locale.ENGLISH.getLanguage())) {
        language = Locale.ENGLISH.getLanguage();
    }
    // if store is not CAD /** maintained in the currency **/
    /*		if (!store.getCurrency().equals(Constants.CURRENCY_CODE_CAD)) {
			total = CurrencyUtil.convertToCurrency(total, store.getCurrency(),
					Constants.CURRENCY_CODE_CAD);
		}*/
    Language lang = store.getDefaultLanguage();
    HttpGet httpget = null;
    Reader xmlreader = null;
    String pack = configuration.getIntegrationOptions().get("packages").get(0);
    try {
        Map<String, Country> countries = countryService.getCountriesMap(lang);
        Country destination = countries.get(delivery.getCountry().getIsoCode());
        Map<String, String> keys = configuration.getIntegrationKeys();
        if (keys == null || StringUtils.isBlank(keys.get("account"))) {
            // TODO can we return null
            return null;
        }
        String host = null;
        String protocol = null;
        String port = null;
        String url = null;
        // against which environment are we using the service
        String env = configuration.getEnvironment();
        // must be US
        if (!store.getCountry().getIsoCode().equals("US")) {
            throw new IntegrationException("Can't use the service for store country code ");
        }
        Map<String, ModuleConfig> moduleConfigsMap = module.getModuleConfigs();
        for (String key : moduleConfigsMap.keySet()) {
            ModuleConfig moduleConfig = moduleConfigsMap.get(key);
            if (moduleConfig.getEnv().equals(env)) {
                host = moduleConfig.getHost();
                protocol = moduleConfig.getScheme();
                port = moduleConfig.getPort();
                url = moduleConfig.getUri();
            }
        }
        StringBuilder xmlheader = new StringBuilder();
        if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
            xmlheader.append("<RateV3Request USERID=\"").append(keys.get("account")).append("\">");
        } else {
            xmlheader.append("<IntlRateRequest USERID=\"").append(keys.get("account")).append("\">");
        }
        StringBuilder xmldatabuffer = new StringBuilder();
        double totalW = 0;
        double totalH = 0;
        double totalL = 0;
        double totalG = 0;
        double totalP = 0;
        for (PackageDetails detail : packages) {
            // need size in inch
            double w = DataUtils.getMeasure(detail.getShippingWidth(), store, MeasureUnit.IN.name());
            double h = DataUtils.getMeasure(detail.getShippingHeight(), store, MeasureUnit.IN.name());
            double l = DataUtils.getMeasure(detail.getShippingLength(), store, MeasureUnit.IN.name());
            totalW = totalW + w;
            totalH = totalH + h;
            totalL = totalL + l;
            // Girth = Length + (Width x 2) + (Height x 2)
            double girth = l + (w * 2) + (h * 2);
            totalG = totalG + girth;
            // need weight in pounds
            double p = DataUtils.getWeight(detail.getShippingWeight(), store, MeasureUnit.LB.name());
            totalP = totalP + p;
        }
        /*			BigDecimal convertedOrderTotal = CurrencyUtil.convertToCurrency(
					orderTotal, store.getCurrency(),
					Constants.CURRENCY_CODE_USD);*/
        // calculate total shipping volume
        // ship date is 3 days from here
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, 3);
        Date newDate = c.getTime();
        SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
        String shipDate = format.format(newDate);
        int i = 1;
        // need pounds and ounces
        int pounds = (int) totalP;
        String ouncesString = String.valueOf(totalP - pounds);
        int ouncesIndex = ouncesString.indexOf(".");
        String ounces = "00";
        if (ouncesIndex > -1) {
            ounces = ouncesString.substring(ouncesIndex + 1);
        }
        String size = "REGULAR";
        if (totalL + totalG <= 64) {
            size = "REGULAR";
        } else if (totalL + totalG <= 108) {
            size = "LARGE";
        } else {
            size = "OVERSIZE";
        }
        /**
         * Domestic <Package ID="1ST"> <Service>ALL</Service>
         * <ZipOrigination>90210</ZipOrigination>
         * <ZipDestination>96698</ZipDestination> <Pounds>8</Pounds>
         * <Ounces>32</Ounces> <Container/> <Size>REGULAR</Size>
         * <Machinable>true</Machinable> </Package>
         *
         * //MAXWEIGHT=70 lbs
         *
         * //domestic container default=VARIABLE whiteSpace=collapse
         * enumeration=VARIABLE enumeration=FLAT RATE BOX enumeration=FLAT
         * RATE ENVELOPE enumeration=LG FLAT RATE BOX
         * enumeration=RECTANGULAR enumeration=NONRECTANGULAR
         *
         * //INTL enumeration=Package enumeration=Postcards or aerogrammes
         * enumeration=Matter for the blind enumeration=Envelope
         *
         * Size May be left blank in situations that do not Size. Defined as
         * follows: REGULAR: package plus girth is 84 inches or less; LARGE:
         * package length plus girth measure more than 84 inches not more
         * than 108 inches; OVERSIZE: package length plus girth is more than
         * 108 but not 130 inches. For example: <Size>REGULAR</Size>
         *
         * International <Package ID="1ST"> <Machinable>true</Machinable>
         * <MailType>Envelope</MailType> <Country>Canada</Country>
         * <Length>0</Length> <Width>0</Width> <Height>0</Height>
         * <ValueOfContents>250</ValueOfContents> </Package>
         *
         * <Package ID="2ND"> <Pounds>4</Pounds> <Ounces>3</Ounces>
         * <MailType>Package</MailType> <GXG> <Length>46</Length>
         * <Width>14</Width> <Height>15</Height> <POBoxFlag>N</POBoxFlag>
         * <GiftFlag>N</GiftFlag> </GXG>
         * <ValueOfContents>250</ValueOfContents> <Country>Japan</Country>
         * </Package>
         */
        xmldatabuffer.append("<Package ID=\"").append(i).append("\">");
        if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
            xmldatabuffer.append("<Service>");
            xmldatabuffer.append("ALL");
            xmldatabuffer.append("</Service>");
            xmldatabuffer.append("<ZipOrigination>");
            xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
            xmldatabuffer.append("</ZipOrigination>");
            xmldatabuffer.append("<ZipDestination>");
            xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
            xmldatabuffer.append("</ZipDestination>");
            xmldatabuffer.append("<Pounds>");
            xmldatabuffer.append(pounds);
            xmldatabuffer.append("</Pounds>");
            xmldatabuffer.append("<Ounces>");
            xmldatabuffer.append(ounces);
            xmldatabuffer.append("</Ounces>");
            xmldatabuffer.append("<Container>");
            xmldatabuffer.append(pack);
            xmldatabuffer.append("</Container>");
            xmldatabuffer.append("<Size>");
            xmldatabuffer.append(size);
            xmldatabuffer.append("</Size>");
            // TODO must be changed if not machinable
            xmldatabuffer.append("<Machinable>true</Machinable>");
            xmldatabuffer.append("<ShipDate>");
            xmldatabuffer.append(shipDate);
            xmldatabuffer.append("</ShipDate>");
        } else {
            // if international
            xmldatabuffer.append("<Pounds>");
            xmldatabuffer.append(pounds);
            xmldatabuffer.append("</Pounds>");
            xmldatabuffer.append("<Ounces>");
            xmldatabuffer.append(ounces);
            xmldatabuffer.append("</Ounces>");
            xmldatabuffer.append("<MailType>");
            xmldatabuffer.append(pack);
            xmldatabuffer.append("</MailType>");
            xmldatabuffer.append("<ValueOfContents>");
            xmldatabuffer.append(productPriceUtils.getAdminFormatedAmount(store, orderTotal));
            xmldatabuffer.append("</ValueOfContents>");
            xmldatabuffer.append("<Country>");
            xmldatabuffer.append(destination.getName());
            xmldatabuffer.append("</Country>");
        }
        // if international & CXG
        /*
			 * xmldatabuffer.append("<CXG>"); xmldatabuffer.append("<Length>");
			 * xmldatabuffer.append(""); xmldatabuffer.append("</Length>");
			 * xmldatabuffer.append("<Width>"); xmldatabuffer.append("");
			 * xmldatabuffer.append("</Width>");
			 * xmldatabuffer.append("<Height>"); xmldatabuffer.append("");
			 * xmldatabuffer.append("</Height>");
			 * xmldatabuffer.append("<POBoxFlag>"); xmldatabuffer.append("");
			 * xmldatabuffer.append("</POBoxFlag>");
			 * xmldatabuffer.append("<GiftFlag>"); xmldatabuffer.append("");
			 * xmldatabuffer.append("</GiftFlag>");
			 * xmldatabuffer.append("</CXG>");
			 */
        /*
			 * xmldatabuffer.append("<Width>"); xmldatabuffer.append(totalW);
			 * xmldatabuffer.append("</Width>");
			 * xmldatabuffer.append("<Length>"); xmldatabuffer.append(totalL);
			 * xmldatabuffer.append("</Length>");
			 * xmldatabuffer.append("<Height>"); xmldatabuffer.append(totalH);
			 * xmldatabuffer.append("</Height>");
			 * xmldatabuffer.append("<Girth>"); xmldatabuffer.append(totalG);
			 * xmldatabuffer.append("</Girth>");
			 */
        xmldatabuffer.append("</Package>");
        String xmlfooter = "</RateV3Request>";
        if (!store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
            xmlfooter = "</IntlRateRequest>";
        }
        StringBuilder xmlbuffer = new StringBuilder().append(xmlheader.toString()).append(xmldatabuffer.toString()).append(xmlfooter);
        LOGGER.debug("USPS QUOTE REQUEST " + xmlbuffer.toString());
        // HttpClient client = new HttpClient();
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            @SuppressWarnings("deprecation") String encoded = java.net.URLEncoder.encode(xmlbuffer.toString());
            String completeUri = url + "?API=RateV3&XML=" + encoded;
            if (!store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
                completeUri = url + "?API=IntlRate&XML=" + encoded;
            }
            // ?API=RateV3
            httpget = new HttpGet(protocol + "://" + host + ":" + port + completeUri);
            // RequestEntity entity = new
            // StringRequestEntity(xmlbuffer.toString(),"text/plain","UTF-8");
            // httpget.setRequestEntity(entity);
            ResponseHandler<String> responseHandler = response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    LOGGER.error("Communication Error with ups quote " + status);
                    throw new ClientProtocolException("UPS quote communication error " + status);
                }
            };
            String data = httpclient.execute(httpget, responseHandler);
            /*			int result = client.executeMethod(httpget);
			if (result != 200) {
				LOGGER.error("Communication Error with usps quote " + result + " "
						+ protocol + "://" + host + ":" + port + url);
				throw new Exception("USPS quote communication error " + result);
			}*/
            // data = httpget.getResponseBodyAsString();
            LOGGER.debug("usps quote response " + data);
            USPSParsedElements parsed = new USPSParsedElements();
            /**
             * <RateV3Response> <Package ID="1ST">
             * <ZipOrigination>44106</ZipOrigination>
             * <ZipDestination>20770</ZipDestination>
             */
            Digester digester = new Digester();
            digester.push(parsed);
            if (store.getCountry().getIsoCode().equals(delivery.getCountry().getIsoCode())) {
                digester.addCallMethod("Error/Description", "setError", 0);
                digester.addCallMethod("RateV3Response/Package/Error/Description", "setError", 0);
                digester.addObjectCreate("RateV3Response/Package/Postage", ShippingOption.class);
                digester.addSetProperties("RateV3Response/Package/Postage", "CLASSID", "optionId");
                digester.addCallMethod("RateV3Response/Package/Postage/MailService", "setOptionName", 0);
                digester.addCallMethod("RateV3Response/Package/Postage/MailService", "setOptionCode", 0);
                digester.addCallMethod("RateV3Response/Package/Postage/Rate", "setOptionPriceText", 0);
                // digester
                // .addCallMethod(
                // "RateV3Response/Package/Postage/Commitment/CommitmentDate",
                // "estimatedNumberOfDays", 0);
                digester.addSetNext("RateV3Response/Package/Postage", "addOption");
            } else {
                digester.addCallMethod("Error/Description", "setError", 0);
                digester.addCallMethod("IntlRateResponse/Package/Error/Description", "setError", 0);
                digester.addObjectCreate("IntlRateResponse/Package/Service", ShippingOption.class);
                digester.addSetProperties("IntlRateResponse/Package/Service", "ID", "optionId");
                digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionName", 0);
                digester.addCallMethod("IntlRateResponse/Package/Service/SvcDescription", "setOptionCode", 0);
                digester.addCallMethod("IntlRateResponse/Package/Service/Postage", "setOptionPriceText", 0);
                // digester.addCallMethod(
                // "IntlRateResponse/Package/Service/SvcCommitments",
                // "setEstimatedNumberOfDays", 0);
                digester.addSetNext("IntlRateResponse/Package/Service", "addOption");
            }
            // <?xml
            // version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager
            // Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The
            // XML document is well formed but the document is not
            // valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse>
            // <?xml version="1.0"?>
            // <IntlRateResponse><Package ID="1"><Error><Number>-2147218046</Number>
            // <Source>IntlPostage;clsIntlPostage.GetCountryAndRestirctedServiceId;clsIntlPostage.CalcAllPostageDimensionsXML;IntlRate.ProcessRequest</Source>
            // <Description>Invalid Country Name</Description><HelpFile></HelpFile><HelpContext>1000440</HelpContext></Error></Package></IntlRateResponse>
            xmlreader = new StringReader(data);
            digester.parse(xmlreader);
            if (!StringUtils.isBlank(parsed.getError())) {
                LOGGER.error("Can't process USPS message= " + parsed.getError());
                throw new IntegrationException(parsed.getError());
            }
            if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {
                LOGGER.error("Can't process USPS statusCode=" + parsed.getStatusCode() + " message= " + parsed.getError());
                throw new IntegrationException(parsed.getError());
            }
            if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {
                LOGGER.warn("No options returned from USPS");
                throw new IntegrationException(parsed.getError());
            }
            /*			String carrier = getShippingMethodDescription(locale);
			// cost is in USD, need to do conversion

			MerchantConfiguration rtdetails = config
					.getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
			int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
			if (rtdetails != null) {

				if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
																				// or
																				// not
																				// quotes
					try {
						displayQuoteDeliveryTime = Integer.parseInt(rtdetails
								.getConfigurationValue1());

					} catch (Exception e) {
						log.error("Display quote is not an integer value ["
								+ rtdetails.getConfigurationValue1() + "]");
					}
				}
			}

			LabelUtil labelUtil = LabelUtil.getInstance();*/
            // Map serviceMap =
            // com.salesmanager.core.util.ShippingUtil.buildServiceMap("usps",locale);
            @SuppressWarnings("unchecked") List<ShippingOption> shippingOptions = parsed.getOptions();
            return shippingOptions;
        }
    } catch (Exception e1) {
        LOGGER.error("Error in USPS shipping quote ", e1);
        throw new IntegrationException(e1);
    } finally {
        if (xmlreader != null) {
            try {
                xmlreader.close();
            } catch (Exception ignore) {
            }
        }
        if (httpget != null) {
            httpget.releaseConnection();
        }
    }
}
Also used : ClientProtocolException(org.apache.http.client.ClientProtocolException) ShippingOrigin(com.salesmanager.core.model.shipping.ShippingOrigin) Date(java.util.Date) DataUtils(com.salesmanager.core.business.utils.DataUtils) LoggerFactory(org.slf4j.LoggerFactory) SimpleDateFormat(java.text.SimpleDateFormat) Delivery(com.salesmanager.core.model.common.Delivery) StringUtils(org.apache.commons.lang3.StringUtils) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ArrayList(java.util.ArrayList) EntityUtils(org.apache.http.util.EntityUtils) Inject(javax.inject.Inject) Language(com.salesmanager.core.model.reference.language.Language) BigDecimal(java.math.BigDecimal) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) Calendar(java.util.Calendar) Locale(java.util.Locale) CustomIntegrationConfiguration(com.salesmanager.core.model.system.CustomIntegrationConfiguration) Map(java.util.Map) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) Constants(com.salesmanager.core.business.constants.Constants) MeasureUnit(com.salesmanager.core.constants.MeasureUnit) CountryService(com.salesmanager.core.business.services.reference.country.CountryService) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) Logger(org.slf4j.Logger) Country(com.salesmanager.core.model.reference.country.Country) Digester(org.apache.commons.digester.Digester) HttpEntity(org.apache.http.HttpEntity) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) IOException(java.io.IOException) Reader(java.io.Reader) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) List(java.util.List) StringReader(java.io.StringReader) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) ResponseHandler(org.apache.http.client.ResponseHandler) ShippingQuoteModule(com.salesmanager.core.modules.integration.shipping.model.ShippingQuoteModule) HttpClients(org.apache.http.impl.client.HttpClients) ProductPriceUtils(com.salesmanager.core.business.utils.ProductPriceUtils) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) Reader(java.io.Reader) StringReader(java.io.StringReader) ClientProtocolException(org.apache.http.client.ClientProtocolException) Language(com.salesmanager.core.model.reference.language.Language) Digester(org.apache.commons.digester.Digester) StringReader(java.io.StringReader) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) Calendar(java.util.Calendar) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) Date(java.util.Date) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) Country(com.salesmanager.core.model.reference.country.Country) SimpleDateFormat(java.text.SimpleDateFormat) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails)

Example 2 with ModuleConfig

use of com.salesmanager.core.model.system.ModuleConfig in project shopizer by shopizer-ecommerce.

the class BeanStreamPayment method sendTransaction.

private Transaction sendTransaction(String orderNumber, MerchantStore store, String transaction, String beanstreamType, TransactionType transactionType, PaymentType paymentType, BigDecimal amount, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
    String agent = "Mozilla/4.0";
    String respText = "";
    Map<String, String> nvp = null;
    DataOutputStream output = null;
    DataInputStream in = null;
    BufferedReader is = null;
    HttpURLConnection conn = null;
    try {
        // transaction = "requestType=BACKEND&merchant_id=300200260&trnType=P&username=carlito&password=shopizer001&orderNumber=caa71106-7e3f-4975-a657-a35904dc32a0&trnCardOwner=Carl Samson&trnCardNumber=5100000020002000&trnExpMonth=10&trnExpYear=14&trnCardCvd=123&trnAmount=77.01&ordName=Carl S&ordAddress1=358 Du Languedoc&ordCity=Victoria&ordProvince=BC&ordPostalCode=V8T2E7&ordCountry=CA&ordPhoneNumber=(444) 555-6666&ordEmailAddress=csamson777@yahoo.com";
        /**
         *			requestType=BACKEND&merchant_id=300200260
         *			&trnType=P
         *			&username=carlito&password=shopizer001
         *			&orderNumber=caa71106-7e3f-4975-a657-a35904dc32a0
         *			&trnCardOwner=Carl Samson
         *			&trnCardNumber=5100000020002000
         *			&trnExpMonth=10
         *			&trnExpYear=14
         *			&trnCardCvd=123
         *			&trnAmount=77.01
         *			&ordName=Carl S
         *			&ordAddress1=378 Du Languedoc
         *			&ordCity=Boucherville
         *			&ordProvince=QC
         *			&ordPostalCode=J3B8J1
         *			&ordCountry=CA
         *			&ordPhoneNumber=(444) 555-6666
         *			&ordEmailAddress=test@yahoo.com
         */
        /**
         *			merchant_id=123456789&requestType=BACKEND
         *			&trnType=P&trnOrderNumber=1234TEST&trnAmount=5.00&trnCardOwner=Joe+Test
         *					&trnCardNumber=4030000010001234
         *					&trnExpMonth=10
         *					&trnExpYear=16
         *					&ordName=Joe+Test
         *					&ordAddress1=123+Test+Street
         *					&ordCity=Victoria
         *					&ordProvince=BC
         *					&ordCountry=CA
         *					&ordPostalCode=V8T2E7
         *					&ordPhoneNumber=5555555555
         *					&ordEmailAddress=joe%40testemail.com
         */
        boolean bSandbox = false;
        if (configuration.getEnvironment().equals("TEST")) {
            // sandbox
            bSandbox = true;
        }
        String server = "";
        ModuleConfig configs = module.getModuleConfigs().get("PROD");
        if (bSandbox) {
            configs = module.getModuleConfigs().get("TEST");
        }
        if (configs == null) {
            throw new IntegrationException("Module not configured for TEST or PROD");
        }
        server = new StringBuffer().append(configs.getScheme()).append("://").append(configs.getHost()).append(":").append(configs.getPort()).append(configs.getUri()).toString();
        URL postURL = new URL(server);
        conn = (HttpURLConnection) postURL.openConnection();
        // Set connection parameters. We need to perform input and output,
        // so set both as true.
        conn.setDoInput(true);
        conn.setDoOutput(true);
        // Set the content type we are POSTing. We impersonate it as
        // encoded form data
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", agent);
        conn.setRequestProperty("Content-Length", String.valueOf(transaction.length()));
        conn.setRequestMethod("POST");
        // get the output stream to POST to.
        output = new DataOutputStream(conn.getOutputStream());
        output.writeBytes(transaction);
        output.flush();
        // Read input from the input stream.
        in = new DataInputStream(conn.getInputStream());
        int rc = conn.getResponseCode();
        if (rc != -1) {
            is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String _line = null;
            while (((_line = is.readLine()) != null)) {
                respText = respText + _line;
            }
            LOGGER.debug("BeanStream response -> " + respText.trim());
            nvp = formatUrlResponse(respText.trim());
        } else {
            throw new IntegrationException("Invalid response from BeanStream, return code is " + rc);
        }
        // check
        // trnApproved=1&trnId=10003067&messageId=1&messageText=Approved&trnOrderNumber=E40089&authCode=TEST&errorType=N&errorFields=
        String transactionApproved = nvp.get("TRNAPPROVED");
        String transactionId = nvp.get("TRNID");
        String messageId = nvp.get("MESSAGEID");
        String messageText = (String) nvp.get("MESSAGETEXT");
        String orderId = (String) nvp.get("TRNORDERNUMBER");
        String authCode = (String) nvp.get("AUTHCODE");
        String errorType = (String) nvp.get("ERRORTYPE");
        String errorFields = (String) nvp.get("ERRORFIELDS");
        if (!StringUtils.isBlank(orderNumber)) {
            nvp.put("INTERNALORDERID", orderNumber);
        }
        if (StringUtils.isBlank(transactionApproved)) {
            throw new IntegrationException("Required field transactionApproved missing from BeanStream response");
        }
        // errors
        if (transactionApproved.equals("0")) {
            merchantLogService.save(new MerchantLog(store, "Can't process BeanStream message " + messageText + " return code id " + messageId));
            IntegrationException te = new IntegrationException("Can't process BeanStream message " + messageText);
            te.setExceptionType(IntegrationException.EXCEPTION_PAYMENT_DECLINED);
            te.setMessageCode("message.payment.beanstream." + messageId);
            te.setErrorCode(IntegrationException.TRANSACTION_EXCEPTION);
            throw te;
        }
        // return parseResponse(type,transaction,respText,nvp,order);
        return this.parseResponse(transactionType, paymentType, nvp, amount);
    } catch (Exception e) {
        if (e instanceof IntegrationException) {
            throw (IntegrationException) e;
        }
        throw new IntegrationException("Error while processing BeanStream transaction", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
    }
}
Also used : IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) InputStreamReader(java.io.InputStreamReader) DataOutputStream(java.io.DataOutputStream) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) DataInputStream(java.io.DataInputStream) URL(java.net.URL) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader) MerchantLog(com.salesmanager.core.model.system.MerchantLog)

Example 3 with ModuleConfig

use of com.salesmanager.core.model.system.ModuleConfig in project shopizer by shopizer-ecommerce.

the class BeanStreamPayment method processTransaction.

private Transaction processTransaction(MerchantStore store, Customer customer, TransactionType type, BigDecimal amount, Payment payment, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
    boolean bSandbox = false;
    if (configuration.getEnvironment().equals("TEST")) {
        // sandbox
        bSandbox = true;
    }
    ModuleConfig configs = module.getModuleConfigs().get("PROD");
    if (bSandbox) {
        configs = module.getModuleConfigs().get("TEST");
    }
    if (configs == null) {
        throw new IntegrationException("Module not configured for TEST or PROD");
    }
    String server = new StringBuffer().append(configs.getScheme()).append("://").append(configs.getHost()).append(":").append(configs.getPort()).append(configs.getUri()).toString();
    HttpURLConnection conn = null;
    try {
        // TODO
        String uniqueId = UUID.randomUUID().toString();
        String orderNumber = uniqueId;
        String amnt = productPriceUtils.getAdminFormatedAmount(store, amount);
        StringBuilder messageString = new StringBuilder();
        String transactionType = "P";
        if (type == TransactionType.AUTHORIZE) {
            transactionType = "PA";
        } else if (type == TransactionType.AUTHORIZECAPTURE) {
            transactionType = "P";
        }
        CreditCardPayment creditCardPayment = (CreditCardPayment) payment;
        messageString.append("requestType=BACKEND&");
        messageString.append("merchant_id=").append(configuration.getIntegrationKeys().get("merchantid")).append("&");
        messageString.append("trnType=").append(transactionType).append("&");
        messageString.append("username=").append(configuration.getIntegrationKeys().get("username")).append("&");
        messageString.append("password=").append(configuration.getIntegrationKeys().get("password")).append("&");
        messageString.append("orderNumber=").append(orderNumber).append("&");
        messageString.append("trnCardOwner=").append(creditCardPayment.getCardOwner()).append("&");
        messageString.append("trnCardNumber=").append(creditCardPayment.getCreditCardNumber()).append("&");
        messageString.append("trnExpMonth=").append(creditCardPayment.getExpirationMonth()).append("&");
        messageString.append("trnExpYear=").append(creditCardPayment.getExpirationYear().substring(2)).append("&");
        messageString.append("trnCardCvd=").append(creditCardPayment.getCredidCardValidationNumber()).append("&");
        messageString.append("trnAmount=").append(amnt).append("&");
        StringBuilder nm = new StringBuilder();
        nm.append(customer.getBilling().getFirstName()).append(" ").append(customer.getBilling().getLastName());
        messageString.append("ordName=").append(nm.toString()).append("&");
        messageString.append("ordAddress1=").append(customer.getBilling().getAddress()).append("&");
        messageString.append("ordCity=").append(customer.getBilling().getCity()).append("&");
        String stateProvince = customer.getBilling().getState();
        if (customer.getBilling().getZone() != null) {
            stateProvince = customer.getBilling().getZone().getCode();
        }
        String countryName = customer.getBilling().getCountry().getIsoCode();
        messageString.append("ordProvince=").append(stateProvince).append("&");
        messageString.append("ordPostalCode=").append(customer.getBilling().getPostalCode().replaceAll("\\s", "")).append("&");
        messageString.append("ordCountry=").append(countryName).append("&");
        messageString.append("ordPhoneNumber=").append(customer.getBilling().getTelephone()).append("&");
        messageString.append("ordEmailAddress=").append(customer.getEmailAddress());
        /**
         * 	purchase (P)
         *  -----------
         *				REQUEST -> merchant_id=123456789&requestType=BACKEND&trnType=P&trnOrderNumber=1234TEST&trnAmount=5.00&trnCardOwner=Joe+Test&trnCardNumber=4030000010001234&trnExpMonth=10&trnExpYear=10&ordName=Joe+Test&ordAddress1=123+Test+Street&ordCity=Victoria&ordProvince=BC&ordCountry=CA&ordPostalCode=V8T2E7&ordPhoneNumber=5555555555&ordEmailAddress=joe%40testemail.com
         *				RESPONSE-> trnApproved=1&trnId=10003067&messageId=1&messageText=Approved&trnOrderNumber=E40089&authCode=TEST&errorType=N&errorFields=&responseType=T&trnAmount=10%2E00&trnDate=1%2F17%2F2008+11%3A36%3A34+AM&avsProcessed=0&avsId=0&avsResult=0&avsAddrMatch=0&avsPostalMatch=0&avsMessage=Address+Verification+not+performed+for+this+transaction%2E&rspCodeCav=0&rspCavResult=0&rspCodeCredit1=0&rspCodeCredit2=0&rspCodeCredit3=0&rspCodeCredit4=0&rspCodeAddr1=0&rspCodeAddr2=0&rspCodeAddr3=0&rspCodeAddr4=0&rspCodeDob=0&rspCustomerDec=&trnType=P&paymentMethod=CC&ref1=&ref2=&ref3=&ref4=&ref5=
         *
         *			pre authorization (PA)
         *			----------------------
         *
         *			Prior to processing a pre-authorization through the API, you must modify the transaction settings in your Beanstream merchant member area to allow for this transaction type.
         *			- Log in to the Beanstream online member area at www.beanstream.com/admin/sDefault.asp.
         *			- Navigate to administration - account admin - order settings in the left menu.
         *			Under the heading �Restrict Internet Transaction Processing Types,� select either of the last two options. The �Purchases or Pre-Authorization Only� option will allow you to process both types of transaction through your web interface. De-selecting the �Restrict Internet Transaction Processing Types� checkbox will allow you to process all types of transactions including returns, voids and pre-auth completions.
         *
         *			capture (PAC) -> requires trnId
         *			-------------
         *
         *			refund (R)
         *			-------------
         *				REQUEST -> merchant_id=123456789&requestType=BACKEND&trnType=R&username=user1234&password=pass1234&trnOrderNumber=1234&trnAmount=1.00&adjId=10002115
         *				RESPONSE-> trnApproved=1&trnId=10002118&messageId=1&messageText=Approved&trnOrderNumber=1234R&authCode=TEST&errorType=N&errorFields=&responseType=T&trnAmount=1%2E00&trnDate=8%2F17%2F2009+1%3A44%3A56+PM&avsProcessed=0&avsId=0&avsResult=0&avsAddrMatch=0&avsPostalMatch=0&avsMessage=Address+Verification+not+performed+for+this+transaction%2E&cardType=VI&trnType=R&paymentMethod=CC&ref1=&ref2=&ref3=&ref4=&ref5=
         *
         *			//notes
         *			//On receipt of the transaction response, the merchant must display order amount, transaction ID number, bank authorization code (authCode), currency, date and �messageText� to the customer on a confirmation page.
         */
        // String agent = "Mozilla/4.0";
        // String respText = "";
        // Map nvp = null;
        /**
         * debug *
         */
        StringBuilder messageLogString = new StringBuilder();
        messageLogString.append("requestType=BACKEND&");
        messageLogString.append("merchant_id=").append(configuration.getIntegrationKeys().get("merchantid")).append("&");
        messageLogString.append("trnType=").append(type).append("&");
        messageLogString.append("orderNumber=").append(orderNumber).append("&");
        messageLogString.append("trnCardOwner=").append(creditCardPayment.getCardOwner()).append("&");
        messageLogString.append("trnCardNumber=").append(CreditCardUtils.maskCardNumber(creditCardPayment.getCreditCardNumber())).append("&");
        messageLogString.append("trnExpMonth=").append(creditCardPayment.getExpirationMonth()).append("&");
        messageLogString.append("trnExpYear=").append(creditCardPayment.getExpirationYear()).append("&");
        messageLogString.append("trnCardCvd=").append(creditCardPayment.getCredidCardValidationNumber()).append("&");
        messageLogString.append("trnAmount=").append(amnt).append("&");
        messageLogString.append("ordName=").append(nm.toString()).append("&");
        messageLogString.append("ordAddress1=").append(customer.getBilling().getAddress()).append("&");
        messageLogString.append("ordCity=").append(customer.getBilling().getCity()).append("&");
        messageLogString.append("ordProvince=").append(stateProvince).append("&");
        messageLogString.append("ordPostalCode=").append(customer.getBilling().getPostalCode()).append("&");
        messageLogString.append("ordCountry=").append(customer.getBilling().getCountry().getName()).append("&");
        messageLogString.append("ordPhoneNumber=").append(customer.getBilling().getTelephone()).append("&");
        messageLogString.append("ordEmailAddress=").append(customer.getEmailAddress());
        /**
         * debug *
         */
        LOGGER.debug("REQUEST SENT TO BEANSTREAM -> " + messageLogString.toString());
        URL postURL = new URL(server);
        conn = (HttpURLConnection) postURL.openConnection();
        return sendTransaction(orderNumber, store, messageString.toString(), transactionType, type, payment.getPaymentType(), amount, configuration, module);
    } catch (Exception e) {
        if (e instanceof IntegrationException)
            throw (IntegrationException) e;
        throw new IntegrationException("Error while processing BeanStream transaction", e);
    } finally {
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception ignore) {
            }
        }
    }
}
Also used : CreditCardPayment(com.salesmanager.core.model.payments.CreditCardPayment) HttpURLConnection(java.net.HttpURLConnection) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) URL(java.net.URL) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException)

Example 4 with ModuleConfig

use of com.salesmanager.core.model.system.ModuleConfig in project shopizer by shopizer-ecommerce.

the class ModuleConfigurationServiceImpl method getIntegrationModules.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public List<IntegrationModule> getIntegrationModules(String module) {
    List<IntegrationModule> modules = null;
    try {
        /**
         * Modules are loaded using
         */
        // PAYMENT_MODULES
        modules = (List<IntegrationModule>) cache.getFromCache("INTEGRATION_M" + module);
        // SHIPPING_MODULES
        if (modules == null) {
            modules = moduleConfigurationRepository.findByModule(module);
            // set json objects
            for (IntegrationModule mod : modules) {
                String regions = mod.getRegions();
                if (regions != null) {
                    Object objRegions = JSONValue.parse(regions);
                    JSONArray arrayRegions = (JSONArray) objRegions;
                    for (Object arrayRegion : arrayRegions) {
                        mod.getRegionsSet().add((String) arrayRegion);
                    }
                }
                String details = mod.getConfigDetails();
                if (details != null) {
                    Map<String, String> objDetails = (Map<String, String>) JSONValue.parse(details);
                    mod.setDetails(objDetails);
                }
                String configs = mod.getConfiguration();
                if (configs != null) {
                    Object objConfigs = JSONValue.parse(configs);
                    JSONArray arrayConfigs = (JSONArray) objConfigs;
                    Map<String, ModuleConfig> moduleConfigs = new HashMap<String, ModuleConfig>();
                    for (Object arrayConfig : arrayConfigs) {
                        Map values = (Map) arrayConfig;
                        String env = (String) values.get("env");
                        ModuleConfig config = new ModuleConfig();
                        config.setScheme((String) values.get("scheme"));
                        config.setHost((String) values.get("host"));
                        config.setPort((String) values.get("port"));
                        config.setUri((String) values.get("uri"));
                        config.setEnv((String) values.get("env"));
                        if (values.get("config1") != null) {
                            config.setConfig1((String) values.get("config1"));
                        }
                        if (values.get("config2") != null) {
                            config.setConfig1((String) values.get("config2"));
                        }
                        moduleConfigs.put(env, config);
                    }
                    mod.setModuleConfigs(moduleConfigs);
                }
            }
            if (this.payments != null) {
                for (ModuleStarter mod : this.payments) {
                    IntegrationModule m = new IntegrationModule();
                    m.setCode(mod.getUniqueCode());
                    m.setModule(Constants.PAYMENT_MODULES);
                    if (CollectionUtils.isNotEmpty(mod.getSupportedCountry())) {
                        m.setRegions(mod.getSupportedCountry().toString());
                        m.setRegionsSet(new HashSet<String>(mod.getSupportedCountry()));
                    }
                    if (!StringUtils.isBlank(mod.getLogo())) {
                        // base 64
                        m.setBinaryImage(mod.getLogo());
                    }
                    if (StringUtils.isNotBlank(mod.getConfigurable())) {
                        m.setConfigurable(mod.getConfigurable());
                    }
                    modules.add(m);
                }
            }
            cache.putInCache(modules, "INTEGRATION_M" + module);
        }
    } catch (Exception e) {
        LOGGER.error("getIntegrationModules()", e);
    }
    return modules;
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.simple.JSONArray) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) ModuleStarter(modules.commons.ModuleStarter) ServiceException(com.salesmanager.core.business.exception.ServiceException) HashMap(java.util.HashMap) Map(java.util.Map) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule)

Example 5 with ModuleConfig

use of com.salesmanager.core.model.system.ModuleConfig in project shopizer by shopizer-ecommerce.

the class UPSParsedElements method getShippingQuotes.

@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote shippingQuote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration configuration, IntegrationModule module, ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {
    Validate.notNull(configuration, "IntegrationConfiguration must not be null for USPS shipping module");
    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }
    BigDecimal total = orderTotal;
    if (packages == null) {
        return null;
    }
    List<ShippingOption> options = null;
    // only applies to Canada and US
    Country country = delivery.getCountry();
    if (!(country.getIsoCode().equals("US") || country.getIsoCode().equals("CA"))) {
        return null;
    // throw new IntegrationException("UPS Not configured for shipping in country " + country.getIsoCode());
    }
    // supports en and fr
    String language = locale.getLanguage();
    if (!language.equals(Locale.FRENCH.getLanguage()) && !language.equals(Locale.ENGLISH.getLanguage())) {
        language = Locale.ENGLISH.getLanguage();
    }
    String pack = configuration.getIntegrationOptions().get("packages").get(0);
    Map<String, String> keys = configuration.getIntegrationKeys();
    String accessKey = keys.get("accessKey");
    String userId = keys.get("userId");
    String password = keys.get("password");
    String host = null;
    String protocol = null;
    String port = null;
    String url = null;
    StringBuilder xmlbuffer = new StringBuilder();
    HttpPost httppost = null;
    BufferedReader reader = null;
    try {
        String env = configuration.getEnvironment();
        Set<String> regions = module.getRegionsSet();
        if (!regions.contains(store.getCountry().getIsoCode())) {
            throw new IntegrationException("Can't use the service for store country code ");
        }
        Map<String, ModuleConfig> moduleConfigsMap = module.getModuleConfigs();
        for (String key : moduleConfigsMap.keySet()) {
            ModuleConfig moduleConfig = moduleConfigsMap.get(key);
            if (moduleConfig.getEnv().equals(env)) {
                host = moduleConfig.getHost();
                protocol = moduleConfig.getScheme();
                port = moduleConfig.getPort();
                url = moduleConfig.getUri();
            }
        }
        StringBuilder xmlreqbuffer = new StringBuilder();
        xmlreqbuffer.append("<?xml version=\"1.0\"?>");
        xmlreqbuffer.append("<AccessRequest>");
        xmlreqbuffer.append("<AccessLicenseNumber>");
        xmlreqbuffer.append(accessKey);
        xmlreqbuffer.append("</AccessLicenseNumber>");
        xmlreqbuffer.append("<UserId>");
        xmlreqbuffer.append(userId);
        xmlreqbuffer.append("</UserId>");
        xmlreqbuffer.append("<Password>");
        xmlreqbuffer.append(password);
        xmlreqbuffer.append("</Password>");
        xmlreqbuffer.append("</AccessRequest>");
        String xmlhead = xmlreqbuffer.toString();
        String weightCode = store.getWeightunitcode();
        String measureCode = store.getSeizeunitcode();
        if (weightCode.equals("KG")) {
            weightCode = "KGS";
        } else {
            weightCode = "LBS";
        }
        String xml = "<?xml version=\"1.0\"?><RatingServiceSelectionRequest><Request><TransactionReference><CustomerContext>Shopizer</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>Rate</RequestAction><RequestOption>Shop</RequestOption></Request>";
        StringBuilder xmldatabuffer = new StringBuilder();
        /**
         * <Shipment>
         *
         * <Shipper> <Address> <City></City>
         * <StateProvinceCode>QC</StateProvinceCode>
         * <CountryCode>CA</CountryCode> <PostalCode></PostalCode>
         * </Address> </Shipper>
         *
         * <ShipTo> <Address> <City>Redwood Shores</City>
         * <StateProvinceCode>CA</StateProvinceCode>
         * <CountryCode>US</CountryCode> <PostalCode></PostalCode>
         * <ResidentialAddressIndicator/> </Address> </ShipTo>
         *
         * <Package> <PackagingType> <Code>21</Code> </PackagingType>
         * <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code>
         * </UnitOfMeasurement> <Weight>1.1</Weight> </PackageWeight>
         * <PackageServiceOptions> <InsuredValue>
         * <CurrencyCode>CAD</CurrencyCode>
         * <MonetaryValue>100</MonetaryValue> </InsuredValue>
         * </PackageServiceOptions> </Package>
         *
         * </Shipment>
         *
         * <CustomerClassification> <Code>03</Code>
         * </CustomerClassification> </RatingServiceSelectionRequest>
         * *
         */
        /**
         *Map countriesMap = (Map) RefCache.getAllcountriesmap(LanguageUtil
         *					.getLanguageNumberCode(locale.getLanguage()));
         *			Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil
         *					.getLanguageNumberCode(locale.getLanguage()));
         *
         *			Country storeCountry = (Country) countriesMap.get(store
         *					.getCountry());
         *
         *			Country customerCountry = (Country) countriesMap.get(customer
         *					.getCustomerCountryId());
         *
         *			int sZone = -1;
         *			try {
         *				sZone = Integer.parseInt(store.getZone());
         *			} catch (Exception e) {
         *				// TODO: handle exception
         *			}
         *
         *			Zone storeZone = (Zone) zonesMap.get(sZone);
         *			Zone customerZone = (Zone) zonesMap.get(customer
         *					.getCustomerZoneId());*
         */
        xmldatabuffer.append("<PickupType><Code>03</Code></PickupType>");
        // xmldatabuffer.append("<Description>Daily Pickup</Description>");
        xmldatabuffer.append("<Shipment><Shipper>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(store.getStorecity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(store.getStorestateprovince())) {
        if (store.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            // zone code
            xmldatabuffer.append(store.getZone().getCode());
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(store.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
        xmldatabuffer.append("</PostalCode></Address></Shipper>");
        // ship to
        xmldatabuffer.append("<ShipTo>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(delivery.getCity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(customer.getCustomerState())) {
        if (delivery.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            // zone code
            xmldatabuffer.append(delivery.getZone().getCode());
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(delivery.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
        xmldatabuffer.append("</PostalCode></Address></ShipTo>");
        for (PackageDetails packageDetail : packages) {
            xmldatabuffer.append("<Package>");
            xmldatabuffer.append("<PackagingType>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(pack);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</PackagingType>");
            // weight
            xmldatabuffer.append("<PackageWeight>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(weightCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Weight>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingWeight()).setScale(1, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Weight>");
            xmldatabuffer.append("</PackageWeight>");
            // dimension
            xmldatabuffer.append("<Dimensions>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(measureCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Length>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingLength()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Length>");
            xmldatabuffer.append("<Width>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingWidth()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Width>");
            xmldatabuffer.append("<Height>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingHeight()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Height>");
            xmldatabuffer.append("</Dimensions>");
            xmldatabuffer.append("</Package>");
        }
        xmldatabuffer.append("</Shipment>");
        xmldatabuffer.append("</RatingServiceSelectionRequest>");
        xmlbuffer.append(xmlhead).append(xml).append(xmldatabuffer.toString());
        LOGGER.debug("UPS QUOTE REQUEST " + xmlbuffer.toString());
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            // HttpClient client = new HttpClient();
            httppost = new HttpPost(protocol + "://" + host + ":" + port + url);
            StringEntity entity = new StringEntity(xmlbuffer.toString(), ContentType.APPLICATION_ATOM_XML);
            // RequestEntity entity = new StringRequestEntity(
            // xmlbuffer.toString(), "text/plain", "UTF-8");
            httppost.setEntity(entity);
            // Create a custom response handler
            ResponseHandler<String> responseHandler = response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity1 = response.getEntity();
                    return entity1 != null ? EntityUtils.toString(entity1) : null;
                } else {
                    LOGGER.error("Communication Error with ups quote " + status);
                    throw new ClientProtocolException("UPS quote communication error " + status);
                }
            };
            String data = httpclient.execute(httppost, responseHandler);
            // int result = response.getStatusLine().getStatusCode();
            // int result = client.executeMethod(httppost);
            /*			if (result != 200) {
				LOGGER.error("Communication Error with ups quote " + result + " "
						+ protocol + "://" + host + ":" + port + url);
				throw new Exception("UPS quote communication error " + result);
			}*/
            LOGGER.debug("ups quote response " + data);
            UPSParsedElements parsed = new UPSParsedElements();
            Digester digester = new Digester();
            digester.push(parsed);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/Error", "setErrorCode", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/ErrorDescriprion", "setError", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusCode", "setStatusCode", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusDescription", "setStatusMessage", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/Error/ErrorDescription", "setError", 0);
            digester.addObjectCreate("RatingServiceSelectionResponse/RatedShipment", ShippingOption.class);
            // digester.addSetProperties(
            // "RatingServiceSelectionResponse/RatedShipment", "sequence",
            // "optionId" );
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionId", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/TotalCharges/MonetaryValue", "setOptionPriceText", 0);
            // digester
            // .addCallMethod(
            // "RatingServiceSelectionResponse/RatedShipment/TotalCharges/CurrencyCode",
            // "setCurrency", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionCode", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/GuaranteedDaysToDelivery", "setEstimatedNumberOfDays", 0);
            digester.addSetNext("RatingServiceSelectionResponse/RatedShipment", "addOption");
            // <?xml
            // version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager
            // Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The
            // XML document is well formed but the document is not
            // valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse>
            Reader xmlreader = new StringReader(data);
            digester.parse(xmlreader);
            if (!StringUtils.isBlank(parsed.getErrorCode())) {
                LOGGER.error("Can't process UPS statusCode=" + parsed.getErrorCode() + " message= " + parsed.getError());
                throw new IntegrationException(parsed.getError());
            }
            if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {
                throw new IntegrationException(parsed.getError());
            }
            if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {
                throw new IntegrationException("No shipping options available for the configuration");
            }
            /*String carrier = getShippingMethodDescription(locale);
			// cost is in CAD, need to do conversion

			boolean requiresCurrencyConversion = false; String storeCurrency
			 = store.getCurrency();
			if(!storeCurrency.equals(Constants.CURRENCY_CODE_CAD)) {
			 requiresCurrencyConversion = true; }

			LabelUtil labelUtil = LabelUtil.getInstance();
			Map serviceMap = com.salesmanager.core.util.ShippingUtil
					.buildServiceMap("upsxml", locale);

			*/
            /**
             * Details on whit RT quote information to display *
             */
            /*
			MerchantConfiguration rtdetails = config
					.getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
			int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
			if (rtdetails != null) {

				if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
																				// or
																				// not
																				// quotes
					try {
						displayQuoteDeliveryTime = Integer.parseInt(rtdetails
								.getConfigurationValue1());

					} catch (Exception e) {
						log.error("Display quote is not an integer value ["
								+ rtdetails.getConfigurationValue1() + "]");
					}
				}
			}*/
            List<ShippingOption> shippingOptions = parsed.getOptions();
            if (shippingOptions != null) {
                Map<String, String> details = module.getDetails();
                for (ShippingOption option : shippingOptions) {
                    String name = details.get(option.getOptionCode());
                    option.setOptionName(name);
                    if (option.getOptionPrice() == null) {
                        String priceText = option.getOptionPriceText();
                        if (StringUtils.isBlank(priceText)) {
                            throw new IntegrationException("Price text is null for option " + name);
                        }
                        try {
                            BigDecimal price = new BigDecimal(priceText);
                            option.setOptionPrice(price);
                        } catch (Exception e) {
                            throw new IntegrationException("Can't convert to numeric price " + priceText);
                        }
                    }
                }
            }
            return shippingOptions;
        }
    } catch (Exception e1) {
        LOGGER.error("UPS quote error", e1);
        throw new IntegrationException(e1);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignore) {
            }
        }
        if (httppost != null) {
            httppost.releaseConnection();
        }
    }
}
Also used : ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpPost(org.apache.http.client.methods.HttpPost) ShippingOrigin(com.salesmanager.core.model.shipping.ShippingOrigin) DataUtils(com.salesmanager.core.business.utils.DataUtils) LoggerFactory(org.slf4j.LoggerFactory) Delivery(com.salesmanager.core.model.common.Delivery) StringUtils(org.apache.commons.lang3.StringUtils) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ArrayList(java.util.ArrayList) EntityUtils(org.apache.http.util.EntityUtils) BigDecimal(java.math.BigDecimal) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) Locale(java.util.Locale) CustomIntegrationConfiguration(com.salesmanager.core.model.system.CustomIntegrationConfiguration) Map(java.util.Map) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) Logger(org.slf4j.Logger) Country(com.salesmanager.core.model.reference.country.Country) Digester(org.apache.commons.digester.Digester) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) Set(java.util.Set) StringEntity(org.apache.http.entity.StringEntity) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) Reader(java.io.Reader) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) List(java.util.List) Validate(org.apache.commons.lang3.Validate) StringReader(java.io.StringReader) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) BufferedReader(java.io.BufferedReader) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) ResponseHandler(org.apache.http.client.ResponseHandler) ShippingQuoteModule(com.salesmanager.core.modules.integration.shipping.model.ShippingQuoteModule) HttpClients(org.apache.http.impl.client.HttpClients) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) Reader(java.io.Reader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) Digester(org.apache.commons.digester.Digester) StringReader(java.io.StringReader) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) BigDecimal(java.math.BigDecimal) ClientProtocolException(org.apache.http.client.ClientProtocolException) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) BufferedReader(java.io.BufferedReader) Country(com.salesmanager.core.model.reference.country.Country) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails)

Aggregations

ModuleConfig (com.salesmanager.core.model.system.ModuleConfig)7 IntegrationException (com.salesmanager.core.modules.integration.IntegrationException)5 IntegrationModule (com.salesmanager.core.model.system.IntegrationModule)4 Map (java.util.Map)4 HttpURLConnection (java.net.HttpURLConnection)3 URL (java.net.URL)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ServiceException (com.salesmanager.core.business.exception.ServiceException)2 DataUtils (com.salesmanager.core.business.utils.DataUtils)2 Delivery (com.salesmanager.core.model.common.Delivery)2 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)2 Country (com.salesmanager.core.model.reference.country.Country)2 PackageDetails (com.salesmanager.core.model.shipping.PackageDetails)2 ShippingConfiguration (com.salesmanager.core.model.shipping.ShippingConfiguration)2 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)2 ShippingOrigin (com.salesmanager.core.model.shipping.ShippingOrigin)2 ShippingQuote (com.salesmanager.core.model.shipping.ShippingQuote)2 CustomIntegrationConfiguration (com.salesmanager.core.model.system.CustomIntegrationConfiguration)2 IntegrationConfiguration (com.salesmanager.core.model.system.IntegrationConfiguration)2