List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity
public StringRequestEntity(String paramString1, String paramString2, String paramString3) throws UnsupportedEncodingException
From source file:com.salesmanager.core.module.impl.integration.payment.PsigateTransactionImpl.java
public GatewayTransactionVO captureTransaction(IntegrationKeys ik, IntegrationProperties props, MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer, CoreModuleService cis) throws TransactionException { // Get capturable transaction PostMethod httppost = null;/* w w w . j av a2 s . com*/ try { // determine production - test environment String host = cis.getCoreModuleServiceProdDomain(); String protocol = cis.getCoreModuleServiceProdProtocol(); String port = cis.getCoreModuleServiceProdPort(); String url = cis.getCoreModuleServiceProdEnv(); if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) { host = cis.getCoreModuleServiceDevDomain(); protocol = cis.getCoreModuleServiceDevProtocol(); port = cis.getCoreModuleServiceDevPort(); url = cis.getCoreModuleServiceDevEnv(); } // Protocol easyhttps = new Protocol("https", new // EasySSLProtocolSocketFactory(), 443); HttpClient client = new HttpClient(); String xml = "<?xml version=\"1.0\"?><AddressValidationRequest xml:lang=\"en-US\"><Request><TransactionReference><CustomerContext>SalesManager Data</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>AV</RequestAction></Request>"; StringBuffer xmldatabuffer = new StringBuffer(); xmldatabuffer.append("<Order>"); xmldatabuffer.append("<StoreID>").append(ik.getUserid()).append("</StoreID>"); xmldatabuffer.append("<Passphrase>").append(ik.getTransactionKey()).append("</Passphrase>"); xmldatabuffer.append("<PaymentType>").append("CC").append("</PaymentType>"); // 0=Sale, 1=PreAuth, 2=PostAuth, 3=Credit, 4=Forced PostAuth xmldatabuffer.append("<CardAction>").append("2").append("</CardAction>"); // For postauth only xmldatabuffer.append("<OrderID>").append(trx.getInternalGatewayOrderId()).append("</OrderID>"); xmldatabuffer.append("</Order>"); /** * xmldatabuffer.append("<CardNumber>").append("").append( * "</CardNumber>"); * xmldatabuffer.append("<CardExpMonth>").append("" * ).append("</CardExpMonth>"); * xmldatabuffer.append("<CardExpYear>") * .append("").append("</CardExpYear>"); //CVV * xmldatabuffer.append("<CustomerIP>" * ).append("").append("</CustomerIP>"); * xmldatabuffer.append("<CardIDNumber>" * ).append("").append("</CardIDNumber>"); * xmldatabuffer.append("</Order>"); **/ log.debug("Psigate request " + xmldatabuffer.toString()); httppost = new PostMethod(protocol + "://" + host + ":" + port + url); RequestEntity entity = new StringRequestEntity(xmldatabuffer.toString(), "text/plain", "UTF-8"); httppost.setRequestEntity(entity); PsigateParsedElements pe = null; String stringresult = null; int result = client.executeMethod(httppost); if (result != 200) { log.error("Communication Error with psigate " + protocol + "://" + host + ":" + port + url); throw new Exception( "Communication Error with psigate " + protocol + "://" + host + ":" + port + url); } stringresult = httppost.getResponseBodyAsString(); log.debug("Psigate response " + stringresult); pe = new PsigateParsedElements(); Digester digester = new Digester(); digester.push(pe); digester.addCallMethod("Result/OrderID", "setOrderID", 0); digester.addCallMethod("Result/Approved", "setApproved", 0); digester.addCallMethod("Result/ErrMsg", "setErrMsg", 0); digester.addCallMethod("Result/ReturnCode", "setReturnCode", 0); digester.addCallMethod("Result/TransRefNumber", "setTransRefNumber", 0); digester.addCallMethod("Result/CardType", "setCardType", 0); Reader reader = new StringReader(stringresult); digester.parse(reader); return this.parseResponse(PaymentConstants.CAPTURE, xmldatabuffer.toString(), stringresult, pe, order, order.getTotal()); } catch (Exception e) { if (e instanceof TransactionException) { throw (TransactionException) e; } log.error(e); TransactionException te = new TransactionException("Psigate Gateway error ", e); te.setErrorcode("01"); throw te; } finally { if (httppost != null) httppost.releaseConnection(); } }
From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java
public void modifyDatastream(String pid, String dsId, String content) throws IOException { StringBuilder uri = new StringBuilder(getBaseUrl()); uri.append("/objects/"); uri.append(pid);//from w w w . j a va 2 s . c o m uri.append("/datastreams/"); uri.append(dsId); PutMethod method = new PutMethod(uri.toString()); method.setRequestEntity(new StringRequestEntity(content, "text/xml", "UTF-8")); executeMethod(method); method.releaseConnection(); }
From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java
private static boolean pollAsyncCgiService(String msName, String url, EndpointReference epr, String[] queryIds, String[] result) throws MobyException { // Needed to remap results HashMap<String, Integer> queryMap = new HashMap<String, Integer>(); for (int qi = 0; qi < queryIds.length; qi++) { String queryId = queryIds[qi]; if (queryId != null) queryMap.put(queryId, new Integer(qi)); }/*from w w w . ja v a2s.co m*/ if (queryMap.size() == 0) return false; // construct the GetMultipleResourceProperties XML StringBuffer xml = new StringBuffer(); xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS + "' xmlns:mobyws='http://biomoby.org/'>"); for (String q : queryMap.keySet()) xml.append("<wsrf-rp:ResourceProperty>mobyws:" + STATUS_PREFIX + q + "</wsrf-rp:ResourceProperty>"); xml.append("</wsrf-rp:GetMultipleResourceProperties>"); StringBuffer httpheader = new StringBuffer(); httpheader.append("<moby-wsrf>"); httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>"); httpheader.append( "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">" + url + "</wsa:To>"); httpheader.append( "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">" + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>"); httpheader.append("</moby-wsrf>"); AnalysisEvent[] l_ae = null; // First, status from queries String response = ""; // construct the Httpclient HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "jMoby/Taverna2"); // create the post method PostMethod method = new PostMethod(url + "/status"); // add the moby-wsrf header (with no newlines) method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", "")); // put our data in the request RequestEntity entity; try { entity = new StringRequestEntity(xml.toString(), "text/xml", null); } catch (UnsupportedEncodingException e) { throw new MobyException("Problem posting data to webservice", e); } method.setRequestEntity(entity); // retry up to 10 times client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(10, true)); // call the method try { if (client.executeMethod(method) != HttpStatus.SC_OK) throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode() + "\n" + method.getStatusLine() + "\nduring our polling request"); response = stream2String(method.getResponseBodyAsStream()); } catch (IOException e) { throw new MobyException("Problem reading response from webservice", e); } finally { // Release current connection to the connection pool once you // are // done method.releaseConnection(); } if (response != null) { l_ae = AnalysisEvent.createFromXML(response); } if (l_ae == null || l_ae.length == 0) { new MobyException("Troubles while checking asynchronous MOBY job status from service " + msName); } ArrayList<String> finishedQueries = new ArrayList<String>(); // Second, gather those finished queries for (int iae = 0; iae < l_ae.length; iae++) { AnalysisEvent ae = l_ae[iae]; if (ae.isCompleted()) { String queryId = ae.getQueryId(); if (!queryMap.containsKey(queryId)) { throw new MobyException( "Invalid result queryId on asynchronous MOBY job status fetched from " + msName); } finishedQueries.add(queryId); } } // Third, let's fetch the results from the finished queries if (finishedQueries.size() > 0) { String[] resQueryIds = finishedQueries.toArray(new String[0]); for (int x = 0; x < resQueryIds.length; x++) { // construct the GetMultipleResourceProperties XML xml = new StringBuffer(); xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS + "' xmlns:mobyws='http://biomoby.org/'>"); for (String q : resQueryIds) xml.append("<wsrf-rp:ResourceProperty>mobyws:" + RESULT_PREFIX + q + "</wsrf-rp:ResourceProperty>"); xml.append("</wsrf-rp:GetMultipleResourceProperties>"); httpheader = new StringBuffer(); httpheader.append("<moby-wsrf>"); httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>"); httpheader.append( "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">" + url + "</wsa:To>"); httpheader.append( "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">" + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>"); httpheader.append("</moby-wsrf>"); client = new HttpClient(); client.getParams().setParameter("http.useragent", "jMoby/Taverna2"); // create the post method method = new PostMethod(url + "/results"); // add the moby-wsrf header (with no newlines) method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", "")); // put our data in the request entity = null; try { entity = new StringRequestEntity(xml.toString(), "text/xml", null); } catch (UnsupportedEncodingException e) { throw new MobyException("Problem posting data to webservice", e); } method.setRequestEntity(entity); // retry up to 10 times client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(10, true)); // call the method try { if (client.executeMethod(method) != HttpStatus.SC_OK) throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode() + "\n" + method.getStatusLine() + "\nduring our polling request"); // place the result in the array result[x] = stream2String(method.getResponseBodyAsStream()); // Marking as null queryIds[x] = null; } catch (IOException e) { logger.warn("Problem getting result from webservice\n" + e.getMessage()); } finally { // Release current connection method.releaseConnection(); } } } return finishedQueries.size() != queryMap.size(); }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same standard POST data * as was sent in the given {@link HttpServletRequest} * * @param methodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to * be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} * @param history The {@link com.groupon.odo.proxylib.models.History} log for this request *//*from ww w. j ava 2s . c o m*/ @SuppressWarnings("unchecked") public static void handleStandardPost(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest, History history) throws Exception { String deserialisedMessages = ""; byte[] requestByteArray = null; // Create a new StringBuffer with the data to be passed StringBuilder requestBody = new StringBuilder(); InputStream body = httpServletRequest.getInputStream(); java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A"); if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_FORM_URLENCODED)) { // Get the client POST data as a Map if content type is: application/x-www-form-urlencoded // We do this manually since some data is not properly parseable by the servlet request Map<String, String[]> mapPostParameters = HttpUtilities.mapUrlEncodedParameters(httpServletRequest); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParameterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list // add an & if there is already data if (requestBody.length() > 0) { requestBody.append("&"); } requestBody.append(stringParameterName); // not everything has a value so lets check if (stringParameterValue.length() > 0) { requestBody.append("="); requestBody.append(stringParameterValue); } } } } else if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { /** * Convert input stream to bytes for it to be read by the deserializer * Unpack and iterate the list to see the contents */ MessagePack msgpack = new MessagePack(); requestByteArray = IOUtils.toByteArray(body); ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(requestByteArray); Unpacker unpacker = msgpack.createUnpacker(byteArrayIS); for (Value message : unpacker) { deserialisedMessages += message; deserialisedMessages += "\n"; } } else { // just set the request body to the POST body if (s.hasNext()) { requestBody.append(s.next()); } } // Set the proxy request data StringRequestEntity stringEntity = new StringRequestEntity(requestBody.toString(), null, null); // set post body in history object history.setRequestPostData(requestBody.toString()); // set post body in proxy request object methodProxyRequest.setRequestEntity(stringEntity); /** * Set the history to have decoded messagepack. Pass the byte data back to request */ if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { history.setRequestPostData(deserialisedMessages); ByteArrayRequestEntity byteRequestEntity = new ByteArrayRequestEntity(requestByteArray); methodProxyRequest.setRequestEntity(byteRequestEntity); } }
From source file:com.buzzdavidson.spork.client.OWAClient.java
public boolean removeMessage(String messageUrl) { boolean retval = false; String filename = messageUrl.substring(messageUrl.lastIndexOf("/") + 1); String query = String.format(OWA_QUERY_DELETE_MESSAGE, filename); WebDavMethod del = new WebDavMethod(inboxAddress + "/", OWA_METHOD_DELETE, OWA_HEADERS_MATCH); try {/*from w w w . ja v a 2s . c o m*/ del.setRequestEntity(new StringRequestEntity(query, null, null)); logger.info("Deleting message [" + filename + "]"); int status = client.executeMethod(del); retval = (status == HttpStatus.SC_OK); if (logger.isDebugEnabled()) { logger.debug("Message request returned status code [" + status + "]"); } } catch (HttpException ex) { logger.error("Received HttpException fetching mail", ex); } catch (UnsupportedEncodingException ex) { logger.error("Received UnsupportedEncodingException fetching mail", ex); } catch (IOException ex) { logger.error("Received IOException fetching mail", ex); } return retval; }
From source file:com.salesmanager.core.module.impl.integration.shipping.CanadaPostQuotesImpl.java
public Collection<ShippingOption> getShippingQuote(ConfigurationResponse config, BigDecimal orderTotal, Collection<PackageDetail> packages, Customer customer, MerchantStore store, Locale locale) { BigDecimal total = orderTotal; if (packages == null) { return null; }/*from w ww . j a va 2s. c o m*/ // only applies to Canada and US if (customer.getCustomerCountryId() != 38 && customer.getCustomerCountryId() != 223) { return null; } // supports en and fr String language = locale.getLanguage(); if (!language.equals(Constants.FRENCH_CODE) && !language.equals(Constants.ENGLISH_CODE)) { language = Constants.ENGLISH_CODE; } // get canadapost credentials if (config == null) { log.error("CanadaPostQuotesImp.getShippingQuote requires ConfigurationVO for key SHP_RT_CRED"); return null; } // if store is not CAD if (!store.getCurrency().equals(Constants.CURRENCY_CODE_CAD)) { total = CurrencyUtil.convertToCurrency(total, store.getCurrency(), Constants.CURRENCY_CODE_CAD); } PostMethod httppost = null; CanadaPostParsedElements canadaPost = null; try { int icountry = store.getCountry(); String country = CountryUtil.getCountryIsoCodeById(icountry); ShippingService sservice = (ShippingService) ServiceFactory.getService(ServiceFactory.ShippingService); CoreModuleService cms = sservice.getRealTimeQuoteShippingService(country, "canadapost"); IntegrationKeys keys = (IntegrationKeys) config.getConfiguration("canadapost-keys"); IntegrationProperties props = (IntegrationProperties) config.getConfiguration("canadapost-properties"); if (cms == null) { // throw new // Exception("Central integration services not configured for " // + PaymentConstants.PAYMENT_PSIGATENAME + " and country id " + // origincountryid); log.error("CoreModuleService not configured for canadapost and country id " + icountry); return null; } String host = cms.getCoreModuleServiceProdDomain(); String protocol = cms.getCoreModuleServiceProdProtocol(); String port = cms.getCoreModuleServiceProdPort(); String url = cms.getCoreModuleServiceProdEnv(); if (props.getProperties1().equals(String.valueOf(ShippingConstants.TEST_ENVIRONMENT))) { host = cms.getCoreModuleServiceDevDomain(); protocol = cms.getCoreModuleServiceDevProtocol(); port = cms.getCoreModuleServiceDevPort(); url = cms.getCoreModuleServiceDevEnv(); } // accept KG and CM StringBuffer request = new StringBuffer(); request.append("<?xml version=\"1.0\" ?>"); request.append("<eparcel>"); request.append("<language>").append(language).append("</language>"); request.append("<ratesAndServicesRequest>"); request.append("<merchantCPCID>").append(keys.getUserid()).append("</merchantCPCID>"); request.append("<fromPostalCode>") .append(com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode())) .append("</fromPostalCode>"); request.append("<turnAroundTime>").append("24").append("</turnAroundTime>"); request.append("<itemsPrice>").append(CurrencyUtil.displayFormatedAmountNoCurrency(total, "CAD")) .append("</itemsPrice>"); request.append("<lineItems>"); Iterator packageIterator = packages.iterator(); while (packageIterator.hasNext()) { PackageDetail pack = (PackageDetail) packageIterator.next(); request.append("<item>"); request.append("<quantity>").append(pack.getShippingQuantity()).append("</quantity>"); request.append("<weight>") .append(String.valueOf( CurrencyUtil.getWeight(pack.getShippingWeight(), store, Constants.KG_WEIGHT_UNIT))) .append("</weight>"); request.append("<length>") .append(String.valueOf( CurrencyUtil.getMeasure(pack.getShippingLength(), store, Constants.CM_SIZE_UNIT))) .append("</length>"); request.append("<width>") .append(String.valueOf( CurrencyUtil.getMeasure(pack.getShippingWidth(), store, Constants.CM_SIZE_UNIT))) .append("</width>"); request.append("<height>") .append(String.valueOf( CurrencyUtil.getMeasure(pack.getShippingHeight(), store, Constants.CM_SIZE_UNIT))) .append("</height>"); request.append("<description>").append(pack.getProductName()).append("</description>"); request.append("<readyToShip/>"); request.append("</item>"); } Country c = null; Map countries = (Map) RefCache .getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage())); c = (Country) countries.get(store.getCountry()); request.append("</lineItems>"); request.append("<city>").append(customer.getCustomerCity()).append("</city>"); request.append("<provOrState>").append(customer.getShippingSate()).append("</provOrState>"); Map cs = (Map) RefCache.getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage())); Country customerCountry = (Country) cs.get(customer.getCustomerCountryId()); request.append("<country>").append(customerCountry.getCountryName()).append("</country>"); request.append("<postalCode>").append( com.salesmanager.core.util.ShippingUtil.trimPostalCode(customer.getCustomerPostalCode())) .append("</postalCode>"); request.append("</ratesAndServicesRequest>"); request.append("</eparcel>"); /** * <?xml version="1.0" ?> <eparcel> * <!--********************************--> <!-- Prefered language * for the --> <!-- response (FR/EN) (optional) --> * <!--********************************--> <language>en</language> * * <ratesAndServicesRequest> * <!--**********************************--> <!-- Merchant * Identification assigned --> <!-- by Canada Post --> <!-- --> <!-- * Note: Use 'CPC_DEMO_HTML' or ask --> <!-- our Help Desk to change * your --> <!-- profile if you want HTML to be --> <!-- returned to * you --> <!--**********************************--> <merchantCPCID> * CPC_DEMO_XML </merchantCPCID> * * <!--*********************************--> <!--Origin Postal Code * --> <!--This parameter is optional --> * <!--*********************************--> * <fromPostalCode>m1p1c0</fromPostalCode> * * <!--**********************************--> <!-- Turn Around Time * (hours) --> <!-- This parameter is optional --> * <!--**********************************--> <turnAroundTime> 24 * </turnAroundTime> * * <!--**********************************--> <!-- Total amount in $ * of the items --> <!-- for insurance calculation --> <!-- This * parameter is optional --> * <!--**********************************--> * <itemsPrice>0.00</itemsPrice> * * <!--**********************************--> <!-- List of items in * the shopping --> <!-- cart --> <!-- Each item is defined by : --> * <!-- - quantity (mandatory) --> <!-- - size (mandatory) --> <!-- * - weight (mandatory) --> <!-- - description (mandatory) --> <!-- * - ready to ship (optional) --> * <!--**********************************--> <lineItems> <item> * <quantity> 1 </quantity> <weight> 1.491 </weight> <length> 1 * </length> <width> 1 </width> <height> 1 </height> <description> * KAO Diskettes </description> </item> * * <item> <quantity> 1 </quantity> <weight> 1.5 </weight> <length> * 20 </length> <width> 30 </width> <height> 20 </height> * <description> My Ready To Ship Item</description> * <!--**********************************************--> <!-- By * adding the 'readyToShip' tag, Sell Online --> <!-- will not pack * this item in the boxes --> <!-- defined in the merchant profile. * --> <!-- Instead, this item will be shipped in its --> <!-- * original box: 1.5 kg and 20x30x20 cm --> * <!--**********************************************--> * <readyToShip/> </item> </lineItems> * * <!--********************************--> <!-- City where the * parcel will be --> <!-- shipped to --> * <!--********************************--> <city> </city> * * <!--********************************--> <!-- Province (Canada) or * State (US)--> <!-- where the parcel will be --> <!-- shipped to * --> <!--********************************--> <provOrState> * Wisconsin </provOrState> * * <!--********************************--> <!-- Country or ISO * Country code --> <!-- where the parcel will be --> <!-- shipped * to --> <!--********************************--> <country> CANADA * </country> * * <!--********************************--> <!-- Postal Code (or ZIP) * where the --> <!-- parcel will be shipped to --> * <!--********************************--> <postalCode> * H3K1E5</postalCode> </ratesAndServicesRequest> </eparcel> **/ log.debug("canadapost request " + request.toString()); HttpClient client = new HttpClient(); StringBuilder u = new StringBuilder().append(protocol).append("://").append(host).append(":") .append(port); if (!StringUtils.isBlank(url)) { u.append(url); } log.debug("Canadapost URL " + u.toString()); httppost = new PostMethod(u.toString()); RequestEntity entity = new StringRequestEntity(request.toString(), "text/plain", "UTF-8"); httppost.setRequestEntity(entity); int result = client.executeMethod(httppost); if (result != 200) { log.error("Communication Error with canadapost " + protocol + "://" + host + ":" + port + url); throw new Exception( "Communication Error with canadapost " + protocol + "://" + host + ":" + port + url); } String stringresult = httppost.getResponseBodyAsString(); log.debug("canadapost response " + stringresult); canadaPost = new CanadaPostParsedElements(); Digester digester = new Digester(); digester.push(canadaPost); digester.addCallMethod("eparcel/ratesAndServicesResponse/statusCode", "setStatusCode", 0); digester.addCallMethod("eparcel/ratesAndServicesResponse/statusMessage", "setStatusMessage", 0); digester.addObjectCreate("eparcel/ratesAndServicesResponse/product", com.salesmanager.core.entity.shipping.ShippingOption.class); digester.addSetProperties("eparcel/ratesAndServicesResponse/product", "sequence", "optionId"); digester.addCallMethod("eparcel/ratesAndServicesResponse/product/shippingDate", "setShippingDate", 0); digester.addCallMethod("eparcel/ratesAndServicesResponse/product/deliveryDate", "setDeliveryDate", 0); digester.addCallMethod("eparcel/ratesAndServicesResponse/product/name", "setOptionName", 0); digester.addCallMethod("eparcel/ratesAndServicesResponse/product/rate", "setOptionPriceText", 0); digester.addSetNext("eparcel/ratesAndServicesResponse/product", "addOption"); /** * response * * <?xml version="1.0" ?> <!DOCTYPE eparcel (View Source for full * doctype...)> - <eparcel> - <ratesAndServicesResponse> * <statusCode>1</statusCode> <statusMessage>OK</statusMessage> * <requestID>1769506</requestID> <handling>0.0</handling> * <language>0</language> - <product id="1040" sequence="1"> * <name>Priority Courier</name> <rate>38.44</rate> * <shippingDate>2008-12-22</shippingDate> * <deliveryDate>2008-12-23</deliveryDate> * <deliveryDayOfWeek>3</deliveryDayOfWeek> * <nextDayAM>true</nextDayAM> <packingID>P_0</packingID> </product> * - <product id="1020" sequence="2"> <name>Expedited</name> * <rate>16.08</rate> <shippingDate>2008-12-22</shippingDate> * <deliveryDate>2008-12-23</deliveryDate> * <deliveryDayOfWeek>3</deliveryDayOfWeek> * <nextDayAM>false</nextDayAM> <packingID>P_0</packingID> * </product> - <product id="1010" sequence="3"> * <name>Regular</name> <rate>16.08</rate> * <shippingDate>2008-12-22</shippingDate> * <deliveryDate>2008-12-29</deliveryDate> * <deliveryDayOfWeek>2</deliveryDayOfWeek> * <nextDayAM>false</nextDayAM> <packingID>P_0</packingID> * </product> - <packing> <packingID>P_0</packingID> - <box> * <name>Small Box</name> <weight>1.691</weight> * <expediterWeight>1.691</expediterWeight> <length>25.0</length> * <width>17.0</width> <height>16.0</height> - <packedItem> * <quantity>1</quantity> <description>KAO Diskettes</description> * </packedItem> </box> - <box> <name>My Ready To Ship Item</name> * <weight>2.0</weight> <expediterWeight>1.5</expediterWeight> * <length>30.0</length> <width>20.0</width> <height>20.0</height> - * <packedItem> <quantity>1</quantity> <description>My Ready To Ship * Item</description> </packedItem> </box> </packing> - * <shippingOptions> <insurance>No</insurance> * <deliveryConfirmation>Yes</deliveryConfirmation> * <signature>No</signature> </shippingOptions> <comment /> * </ratesAndServicesResponse> </eparcel> - <!-- END_OF_EPARCEL --> */ Reader reader = new StringReader(stringresult); digester.parse(reader); } catch (Exception e) { log.error(e); } finally { if (httppost != null) { httppost.releaseConnection(); } } if (canadaPost == null || canadaPost.getStatusCode() == null) { return null; } if (canadaPost.getStatusCode().equals("-6") || canadaPost.getStatusCode().equals("-7")) { LogMerchantUtil.log(store.getMerchantId(), "Can't process CanadaPost statusCode=" + canadaPost.getStatusCode() + " message= " + canadaPost.getStatusMessage()); } if (!canadaPost.getStatusCode().equals("1")) { log.error("An error occured with canadapost request (code-> " + canadaPost.getStatusCode() + " message-> " + canadaPost.getStatusMessage() + ")"); return null; } 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; } /** 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 options = canadaPost.getOptions(); if (options != null) { Iterator i = options.iterator(); while (i.hasNext()) { ShippingOption option = (ShippingOption) i.next(); option.setCurrency(store.getCurrency()); StringBuffer description = new StringBuffer(); description.append(option.getOptionName()); if (displayQuoteDeliveryTime == ShippingConstants.DISPLAY_RT_QUOTE_TIME) { description.append(" (").append(option.getDeliveryDate()).append(")"); } option.setDescription(description.toString()); if (requiresCurrencyConversion) { option.setOptionPrice(CurrencyUtil.convertToCurrency(option.getOptionPrice(), Constants.CURRENCY_CODE_CAD, store.getCurrency())); } // System.out.println(option.getOptionPrice().toString()); } } return options; }
From source file:com.cloud.network.bigswitch.BigSwitchBcfApi.java
protected <T> String executeCreateObject(final T newObject, final String uri, final Map<String, String> parameters) throws BigSwitchBcfApiException { checkInvariants();//from w w w.j a v a2s .co m PostMethod pm = (PostMethod) createMethod("post", uri, _port); setHttpHeader(pm); try { pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null)); } catch (UnsupportedEncodingException e) { throw new BigSwitchBcfApiException("Failed to encode json request body", e); } executeMethod(pm); String hash = checkResponse(pm, "BigSwitch HTTP create failed: "); pm.releaseConnection(); return hash; }
From source file:at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient.java
private static Element sendSOAPRequest(String webServiceURL, Element request) throws MISSimpleClientException { // try { // System.out.println("REQUEST-MIS: \n" + DOMUtils.serializeNode(request)); // } catch (TransformerException e1) { // e1.printStackTrace(); // } catch (IOException e1) { // e1.printStackTrace(); // }// w ww. jav a 2 s . c o m if (webServiceURL == null) { throw new NullPointerException("Argument webServiceURL must not be null."); } if (request == null) { throw new NullPointerException("Argument request must not be null."); } try { HttpClient httpclient = HttpClientWithProxySupport.getHttpClient(); PostMethod post = new PostMethod(webServiceURL); StringRequestEntity re = new StringRequestEntity(DOMUtils.serializeNode(packIntoSOAP(request)), "text/xml", "UTF-8"); post.setRequestEntity(re); int responseCode = httpclient.executeMethod(post); if (responseCode != 200) { throw new MISSimpleClientException("Invalid HTTP response code " + responseCode); } //Element elem = parse(post.getResponseBodyAsStream()); Document doc = DOMUtils.parseDocumentSimple(post.getResponseBodyAsStream()); return unpackFromSOAP(doc.getDocumentElement()); } catch (IOException e) { throw new MISSimpleClientException("service.04", e); } catch (TransformerException e) { throw new MISSimpleClientException("service.06", e); } catch (SAXException e) { throw new MISSimpleClientException("service.06", e); } catch (ParserConfigurationException e) { throw new MISSimpleClientException("service.06", e); } catch (Exception e) { throw new MISSimpleClientException("service.06", e); } }
From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java
private String postRequest(String path, NameValuePair[] params) throws UnsupportedEncodingException { PostMethod httppost = new PostMethod(this.baseURL + path); httppost.setRequestEntity(new StringRequestEntity(nameValueToJson(params), "application/json", "UTF-8")); return postRequest(httppost); }
From source file:jeeves.utils.XmlRequest.java
private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException { HttpMethodBase httpMethod;/*from w ww . java 2 s . c om*/ if (method == Method.GET) { httpMethod = new GetMethod(); if (query != null && !query.equals("")) httpMethod.setQueryString(query); else if (alSimpleParams.size() != 0) httpMethod.setQueryString(alSimpleParams.toArray(new NameValuePair[alSimpleParams.size()])); httpMethod.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml"); httpMethod.setFollowRedirects(true); } else { PostMethod post = new PostMethod(); if (!useSOAP) { postData = (postParams == null) ? "" : Xml.getString(new Document(postParams)); post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8")); } else { postData = Xml.getString(new Document(soapEmbed(postParams))); post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8")); } httpMethod = post; } httpMethod.setPath(address); httpMethod.setDoAuthentication(useAuthent()); return httpMethod; }