List of usage examples for org.apache.commons.httpclient HttpVersion HTTP_1_0
HttpVersion HTTP_1_0
To view the source code for org.apache.commons.httpclient HttpVersion HTTP_1_0.
Click Source Link
From source file:com.predic8.membrane.integration.Http10Test.java
@Test public void testPost() throws Exception { HttpClient client = new HttpClient(); client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); PostMethod post = new PostMethod("http://localhost:3000/axis2/services/BLZService"); InputStream stream = this.getClass().getResourceAsStream("/getBank.xml"); InputStreamRequestEntity entity = new InputStreamRequestEntity(stream); post.setRequestEntity(entity);/*from www . j a v a 2s.com*/ post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8); post.setRequestHeader(Header.SOAP_ACTION, "\"\""); int status = client.executeMethod(post); assertEquals(200, status); assertEquals("HTTP/1.1", post.getStatusLine().getHttpVersion()); String response = post.getResponseBodyAsString(); assertNotNull(response); assertTrue(response.length() > 0); }
From source file:com.collabnet.svnedge.net.CommonsHTTPProxySender.java
@Override protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL url) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (this.proxyUser != null) { client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword)); }//from w w w .j a v a 2s .c o m setupHttpClient(client, url.toString()); // This needs to be set to 1.0 otherwise errors client.getHostConfiguration().getParams().setParameter(HttpClientParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); httpClient = client; return client.getHostConfiguration(); }
From source file:com.predic8.membrane.integration.Http10Test.java
@Test public void testMultiplePost() throws Exception { HttpClient client = new HttpClient(); client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); PostMethod post = new PostMethod("http://localhost:3000/axis2/services/BLZService"); InputStream stream = this.getClass().getResourceAsStream("/getBank.xml"); InputStreamRequestEntity entity = new InputStreamRequestEntity(stream); post.setRequestEntity(entity);// ww w . j a v a 2s .co m post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8); post.setRequestHeader(Header.SOAP_ACTION, "\"\""); for (int i = 0; i < 100; i++) { //System.out.println("Iteration: " + i); int status = client.executeMethod(post); assertEquals(200, status); String response = post.getResponseBodyAsString(); assertNotNull(response); assertTrue(response.length() > 0); } }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpSettingsRequestFilter.java
public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> httpRequest) { ExtendedHttpMethod httpMethod = (ExtendedHttpMethod) context .getProperty(BaseHttpRequestTransport.HTTP_METHOD); // set maxsize Settings settings = httpRequest.getSettings(); // close connections? if (settings.getBoolean(HttpSettings.CLOSE_CONNECTIONS)) { httpMethod.setRequestHeader("Connection", "close"); }/*w w w . j a v a2 s. c o m*/ // close connections? if (settings.getBoolean(HttpSettings.EXPECT_CONTINUE) && httpMethod instanceof EntityEnclosingMethod) { httpMethod.getParams().setParameter(HttpMethodParams.USE_EXPECT_CONTINUE, Boolean.TRUE); } // compress request? String compressionAlg = settings.getString(HttpSettings.REQUEST_COMPRESSION, "None"); if (!"None".equals(compressionAlg)) httpMethod.setRequestHeader("Content-Encoding", compressionAlg); // accept compressed responses? if (settings.getBoolean(HttpSettings.RESPONSE_COMPRESSION)) { httpMethod.setRequestHeader("Accept-Encoding", CompressionSupport.getAvailableAlgorithms(",")); } String httpVersion = settings.getString(HttpSettings.HTTP_VERSION, "1.1"); if (httpVersion.equals(HttpSettings.HTTP_VERSION_1_1)) { httpMethod.getParams().setVersion(HttpVersion.HTTP_1_1); } else if (httpVersion.equals(HttpSettings.HTTP_VERSION_1_0)) { httpMethod.getParams().setVersion(HttpVersion.HTTP_1_0); } else if (httpVersion.equals(HttpSettings.HTTP_VERSION_0_9)) { httpMethod.getParams().setVersion(HttpVersion.HTTP_1_1); } // max size.. long maxSize = httpRequest.getMaxSize(); if (maxSize == 0) maxSize = settings.getLong(HttpSettings.MAX_RESPONSE_SIZE, 0); if (maxSize > 0) httpMethod.setMaxSize(maxSize); // follow redirects is false; handled in transport httpMethod.setFollowRedirects(false); // apply global settings HttpClientSupport.applyHttpSettings(httpMethod, settings); String timeout = context.expand(httpRequest.getTimeout()); if (StringUtils.hasContent(timeout)) { try { httpMethod.getParams().setSoTimeout(Integer.parseInt(timeout)); } catch (NumberFormatException e) { SoapUI.logError(e); } } }
From source file:com.iflytek.spider.protocol.httpclient.HttpResponse.java
/** * Fetches the given <code>url</code> and prepares HTTP response. * /*w w w . jav a 2 s. c o m*/ * @param http * An instance of the implementation class of this plugin * @param url * URL to be fetched * @param datum * Crawl data * @param followRedirects * Whether to follow redirects; follows redirect if and only if * this is true * @return HTTP response * @throws IOException * When an error occurs */ HttpResponse(Http http, URL url, CrawlDatum datum, boolean followRedirects) throws IOException { // Prepare GET method for HTTP request this.url = url; GetMethod get = new GetMethod(url.toString()); get.setFollowRedirects(followRedirects); get.setDoAuthentication(true); if (datum.getModifiedTime() > 0) { get.setRequestHeader("If-Modified-Since", HttpDateFormat.toString(datum.getModifiedTime())); } // Set HTTP parameters HttpMethodParams params = get.getParams(); if (http.getUseHttp11()) { params.setVersion(HttpVersion.HTTP_1_1); } else { params.setVersion(HttpVersion.HTTP_1_0); } params.makeLenient(); params.setContentCharset("UTF-8"); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true); // XXX (ab) not sure about this... the default is to retry 3 times; if // XXX the request body was sent the method is not retried, so there is // XXX little danger in retrying... // params.setParameter(HttpMethodParams.RETRY_HANDLER, null); try { code = Http.getClient().executeMethod(get); Header[] heads = get.getResponseHeaders(); for (int i = 0; i < heads.length; i++) { headers.set(heads[i].getName(), heads[i].getValue()); } // Limit download size int contentLength = Integer.MAX_VALUE; String contentLengthString = headers.get(Response.CONTENT_LENGTH); if (contentLengthString != null) { try { contentLength = Integer.parseInt(contentLengthString.trim()); } catch (NumberFormatException ex) { throw new HttpException("bad content length: " + contentLengthString); } } if (http.getMaxContent() >= 0 && contentLength > http.getMaxContent()) { contentLength = http.getMaxContent(); } // always read content. Sometimes content is useful to find a cause // for error. InputStream in = get.getResponseBodyAsStream(); try { byte[] buffer = new byte[HttpBase.BUFFER_SIZE]; int bufferFilled = 0; int totalRead = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((bufferFilled = in.read(buffer, 0, buffer.length)) != -1 && totalRead < contentLength) { totalRead += bufferFilled; out.write(buffer, 0, bufferFilled); } content = out.toByteArray(); } catch (Exception e) { if (code == 200) throw new IOException(e.toString()); // for codes other than 200 OK, we are fine with empty content } finally { in.close(); get.abort(); } StringBuilder fetchTrace = null; if (Http.LOG.isTraceEnabled()) { // Trace message fetchTrace = new StringBuilder( "url: " + url + "; status code: " + code + "; bytes received: " + content.length); if (getHeader(Response.CONTENT_LENGTH) != null) fetchTrace.append("; Content-Length: " + getHeader(Response.CONTENT_LENGTH)); if (getHeader(Response.LOCATION) != null) fetchTrace.append("; Location: " + getHeader(Response.LOCATION)); } // Extract gzip, x-gzip and deflate content if (content != null) { // check if we have to uncompress it String contentEncoding = headers.get(Response.CONTENT_ENCODING); if (contentEncoding != null && Http.LOG.isTraceEnabled()) fetchTrace.append("; Content-Encoding: " + contentEncoding); if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { content = http.processGzipEncoded(content, url); if (Http.LOG.isTraceEnabled()) fetchTrace.append("; extracted to " + content.length + " bytes"); } else if ("deflate".equals(contentEncoding)) { content = http.processDeflateEncoded(content, url); if (Http.LOG.isTraceEnabled()) fetchTrace.append("; extracted to " + content.length + " bytes"); } } // Log trace message if (Http.LOG.isTraceEnabled()) { Http.LOG.trace(fetchTrace); } } finally { get.releaseConnection(); } }
From source file:com.iflytek.spider.protocol.httpclient.HttpResponseSmiply.java
/** * Fetches the given <code>url</code> and prepares HTTP response. * /* w w w. j a v a 2 s . c om*/ * @param http * An instance of the implementation class of this plugin * @param url * URL to be fetched * @param datum * Crawl data * @param followRedirects * Whether to follow redirects; follows redirect if and only if * this is true * @return HTTP response * @throws IOException * When an error occurs */ HttpResponseSmiply(HttpSimply http, URL url, CrawlDatum datum, boolean followRedirects) throws IOException { // Prepare GET method for HTTP request this.url = url; GetMethod get = new GetMethod(url.toString()); get.setFollowRedirects(followRedirects); get.setDoAuthentication(true); if (datum.getModifiedTime() > 0) { get.setRequestHeader("If-Modified-Since", HttpDateFormat.toString(datum.getModifiedTime())); } // Set HTTP parameters HttpMethodParams params = get.getParams(); if (http.getUseHttp11()) { params.setVersion(HttpVersion.HTTP_1_1); } else { params.setVersion(HttpVersion.HTTP_1_0); } params.makeLenient(); params.setContentCharset("UTF-8"); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true); // XXX (ab) not sure about this... the default is to retry 3 times; if // XXX the request body was sent the method is not retried, so there is // XXX little danger in retrying... // params.setParameter(HttpMethodParams.RETRY_HANDLER, null); try { code = HttpSimply.getClient().executeMethod(get); Header[] heads = get.getResponseHeaders(); for (int i = 0; i < heads.length; i++) { headers.set(heads[i].getName(), heads[i].getValue()); } // Limit download size int contentLength = Integer.MAX_VALUE; String contentLengthString = headers.get(Response.CONTENT_LENGTH); if (contentLengthString != null) { try { contentLength = Integer.parseInt(contentLengthString.trim()); } catch (NumberFormatException ex) { throw new HttpException("bad content length: " + contentLengthString); } } if (http.getMaxContent() >= 0 && contentLength > http.getMaxContent()) { contentLength = http.getMaxContent(); } // always read content. Sometimes content is useful to find a cause // for error. InputStream in = get.getResponseBodyAsStream(); try { byte[] buffer = new byte[HttpBaseSimply.BUFFER_SIZE]; int bufferFilled = 0; int totalRead = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((bufferFilled = in.read(buffer, 0, buffer.length)) != -1 && totalRead < contentLength) { totalRead += bufferFilled; out.write(buffer, 0, bufferFilled); } content = out.toByteArray(); } catch (Exception e) { if (code == 200) throw new IOException(e.toString()); // for codes other than 200 OK, we are fine with empty content } finally { in.close(); get.abort(); } StringBuilder fetchTrace = null; if (Http.LOG.isTraceEnabled()) { // Trace message fetchTrace = new StringBuilder( "url: " + url + "; status code: " + code + "; bytes received: " + content.length); if (getHeader(Response.CONTENT_LENGTH) != null) fetchTrace.append("; Content-Length: " + getHeader(Response.CONTENT_LENGTH)); if (getHeader(Response.LOCATION) != null) fetchTrace.append("; Location: " + getHeader(Response.LOCATION)); } // Extract gzip, x-gzip and deflate content if (content != null) { // check if we have to uncompress it String contentEncoding = headers.get(Response.CONTENT_ENCODING); if (contentEncoding != null && Http.LOG.isTraceEnabled()) fetchTrace.append("; Content-Encoding: " + contentEncoding); if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { content = http.processGzipEncoded(content, url); if (Http.LOG.isTraceEnabled()) fetchTrace.append("; extracted to " + content.length + " bytes"); } else if ("deflate".equals(contentEncoding)) { content = http.processDeflateEncoded(content, url); if (Http.LOG.isTraceEnabled()) fetchTrace.append("; extracted to " + content.length + " bytes"); } } // Log trace message if (Http.LOG.isTraceEnabled()) { Http.LOG.trace(fetchTrace); } } finally { get.releaseConnection(); } }
From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSink2Test.java
/** * Test that the deferredTask handler is installed. *//*w w w . j ava 2s . c o m*/ public void testDeferredTask() throws Exception { // Replace the API proxy delegate so we can fake API responses. FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate(); ApiProxy.setDelegate(fakeApiProxy); // Add a api response so the task queue api is happy. TaskQueueBulkAddResponse taskAddResponse = new TaskQueueBulkAddResponse(); TaskResult taskResult = taskAddResponse.addTaskResult(); taskResult.setResult(ErrorCode.OK.getValue()); taskResult.setChosenTaskName("abc"); fakeApiProxy.addApiResponse(taskAddResponse); // Issue a deferredTaskRequest with payload. String testData = "0987654321acbdefghijklmn"; String[] lines = fetchUrl(createUrl("/testTaskQueue?deferredTask=1&deferredData=" + testData)); TaskQueueBulkAddRequest request = new TaskQueueBulkAddRequest(); request.parseFrom(fakeApiProxy.getLastRequest().requestData); assertEquals(1, request.addRequestSize()); TaskQueueAddRequest addRequest = request.getAddRequest(0); assertEquals(TaskQueueAddRequest.RequestMethod.POST.getValue(), addRequest.getMethod()); // Pull out the request and fire it at the app. HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); PostMethod post = new PostMethod(createUrl(addRequest.getUrl()).toString()); post.getParams().setVersion(HttpVersion.HTTP_1_0); // Add the required Task queue header, plus any headers from the request. post.addRequestHeader("X-AppEngine-QueueName", "1"); for (TaskQueueAddRequest.Header header : addRequest.headers()) { post.addRequestHeader(header.getKey(), header.getValue()); } post.setRequestEntity(new ByteArrayRequestEntity(addRequest.getBodyAsBytes())); int httpCode = httpClient.executeMethod(post); assertEquals(HttpURLConnection.HTTP_OK, httpCode); // Verify that the task was handled and that the payload is correct. lines = fetchUrl(createUrl("/testTaskQueue?getLastPost=1")); assertEquals("deferredData:" + testData, lines[lines.length - 1]); }
From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * /*from w ww. j av a2 s . c om*/ * @param msgContext * the messsage context * * @throws AxisFault */ public void invoke(MessageContext msgContext) throws AxisFault { HttpMethodBase method = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); } try { URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); // no need to retain these, as the cookies/credentials are // stored in the message context across multiple requests. // the underlying connection manager, however, is retained // so sockets get recycled when possible. HttpClient httpClient = new HttpClient(this.connectionManager); // the timeout value for allocation of connections from the pool httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout()); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new RetryHandler()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL); boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) { posting = webMethod.equals(HTTPConstants.HEADER_POST); } } if (posting) { Message reqMessage = msgContext.getRequestMessage(); method = new PostMethod(targetURL.toString()); // set false as default, addContetInfo can overwrite method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); addContextInfo(method, httpClient, msgContext, targetURL); MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream); } else { requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream); } ((PostMethod) method).setRequestEntity(requestEntity); } else { method = new GetMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); } String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null) { if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) { method.getParams().setVersion(HttpVersion.HTTP_1_0); } // assume 1.1 } // don't forget the cookies! // Cookies need to be set on HttpState, since HttpMethodBase // overwrites the cookies from HttpState if (msgContext.getMaintainSession()) { HttpState state = httpClient.getState(); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String host = hostConfiguration.getHost(); String path = targetURL.getPath(); boolean secure = hostConfiguration.getProtocol().isSecure(); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure); httpClient.setState(state); } int returnCode = httpClient.executeMethod(hostConfiguration, method, null); String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION); String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { String statusMessage = method.getStatusText(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); try { fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString())); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } finally { method.releaseConnection(); // release connection back to // pool. } } // wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method); Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); } else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP // message Header[] responseHeaders = method.getResponseHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { if (null == contentLength) { log.debug("\n" + Messages.getMessage("no00", "Content-Length")); } log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) { handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext); } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) { handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext); } } } // always release the connection back to the pool if // it was one way invocation if (msgContext.isPropertyTrue("axis.one.way")) { method.releaseConnection(); } } catch (Exception e) { log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); } }
From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext/*from w w w.ja v a 2 s.co m*/ * the messsage context * * @throws AxisFault */ public void invoke(MessageContext msgContext) throws AxisFault { HttpMethodBase method = null; log.debug(Messages.getMessage("enter00", "CommonsHttpSender::invoke")); try { URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); // no need to retain these, as the cookies/credentials are // stored in the message context across multiple requests. // the underlying connection manager, however, is retained // so sockets get recycled when possible. HttpClient httpClient = new HttpClient(this.connectionManager); // the timeout value for allocation of connections from the pool httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL); boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } if (posting) { Message reqMessage = msgContext.getRequestMessage(); method = new PostMethod(targetURL.toString()); log.info("POST message created with target [" + targetURL.toString() + "]"); TransactionContext transactionContext = TransactionContextFactory.get(); transactionContext .addDebugInformation("POST message created with target [" + targetURL.toString() + "]"); // set false as default, addContetInfo can overwrite method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); addContextInfo(method, httpClient, msgContext, targetURL); Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY); if (cred instanceof UsernamePasswordCredentials) { log.trace("POST message created on client with credentials [" + ((UsernamePasswordCredentials) cred).getUserName() + ", " + ((UsernamePasswordCredentials) cred).getPassword() + "]."); } MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream); log.info("HTTPCommonsSender - zipping request."); } else { requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream); log.info("HTTPCommonsSender - not zipping request"); } ((PostMethod) method).setRequestEntity(requestEntity); } else { method = new GetMethod(targetURL.toString()); log.info("GET message created with target [" + targetURL.toString() + "]"); addContextInfo(method, httpClient, msgContext, targetURL); } if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) log.info("HTTPCommonsSender - accepting GZIP"); else log.info("HTTPCommonsSender - NOT accepting GZIP"); String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) method.getParams().setVersion(HttpVersion.HTTP_1_0); // don't forget the cookies! // Cookies need to be set on HttpState, since HttpMethodBase // overwrites the cookies from HttpState if (msgContext.getMaintainSession()) { HttpState state = httpClient.getState(); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String host = hostConfiguration.getHost(); String path = targetURL.getPath(); boolean secure = hostConfiguration.getProtocol().isSecure(); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure); httpClient.setState(state); } // add HTTP header fields that the application thinks are "interesting" // the expectation is that these would be non-standard HTTP headers, // by convention starting with "xxx-" VistaRealmPrincipal principal = VistaRealmSecurityContext.get(); if (principal != null) { log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available."); String duz = principal.getDuz(); if (duz != null && duz.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz); String fullname = principal.getFullName(); if (fullname != null && fullname.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname); String sitename = principal.getSiteName(); if (sitename != null && sitename.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename); String sitenumber = principal.getSiteNumber(); if (sitenumber != null && sitenumber.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber); String ssn = principal.getSsn(); if (ssn != null && ssn.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn); String securityToken = principal.getSecurityToken(); if (securityToken != null && securityToken.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId, securityToken); String cacheLocationId = principal.getCacheLocationId(); if (cacheLocationId != null && cacheLocationId.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId, cacheLocationId); String userDivision = principal.getUserDivision(); if (userDivision != null && userDivision.length() > 0) method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision); } else log.debug("SecurityContext credentials are NOT available."); method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store"); method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache"); try { log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL() + "]"); } catch (IllegalStateException isX) { } // send the HTTP request and wait for a response int returnCode = httpClient.executeMethod(hostConfiguration, method, null); TransactionContext transactionContext = TransactionContextFactory.get(); // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source //transactionContext.setResponseCode (String.valueOf (returnCode)); // How many bytes received? transactionContext.setDataSourceBytesReceived(method.getBytesReceived()); // How long did it take to start getting a response coming back? Long timeSent = method.getTimeRequestSent(); Long timeReceived = method.getTimeFirstByteReceived(); if (timeSent != null && timeReceived != null) { long timeTook = timeReceived.longValue() - timeSent.longValue(); transactionContext.setTimeToFirstByte(new Long(timeTook)); } // Looks like it wasn't found in cache - is there a place to set this to true if it was? transactionContext.setItemCached(Boolean.FALSE); // extract the basic HTTP header fields for content type, location and length String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION); String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { String statusMessage = method.getStatusText(); try { log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL() + "] failed - '" + statusMessage + "'."); } catch (IllegalStateException isX) { } AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); try { fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString())); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } finally { method.releaseConnection(); // release connection back to // pool. } } // wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method); Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "=" + (contentEncoding == null ? "null" : contentEncoding.getValue())); if (contentEncoding != null) { if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); log.debug("HTTPCommonsSender - receiving gzipped stream."); } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) { releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream( releaseConnectionOnCloseStream); log.debug("HTTPCommonsSender - receiving 'deflated' stream."); } else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); log.warn(fault.getMessage()); throw fault; } } try { log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL() + "] succeeded, parsing response."); } catch (IllegalStateException isX) { } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP // message Header[] responseHeaders = method.getResponseHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isTraceEnabled()) { if (null == contentLength) log.trace("\n" + Messages.getMessage("no00", "Content-Length")); log.trace("\n" + Messages.getMessage("xmlRecd00")); log.trace("-----------------------------------------------"); log.trace(outMsg.getSOAPPartAsString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) { handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext); } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) { handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext); } } } // always release the connection back to the pool if // it was one way invocation if (msgContext.isPropertyTrue("axis.one.way")) { method.releaseConnection(); } } catch (Exception e) { log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); } }
From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and then * reads the response SOAP message back from the SOAP server * * @param msgContext the messsage context * * @throws AxisFault//from w w w. ja va2 s .c o m */ public void invoke(MessageContext msgContext) throws AxisFault { //test(); HttpMethodBase method = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); } try { URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); // no need to retain these, as the cookies/credentials are // stored in the message context across multiple requests. // the underlying connection manager, however, is retained // so sockets get recycled when possible. //org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG); HttpClient httpClient = new HttpClient(this.connectionManager); // the timeout value for allocation of connections from the pool httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL); boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) { posting = webMethod.equals(HTTPConstants.HEADER_POST); } } if (posting) { Message reqMessage = msgContext.getRequestMessage(); method = new PostMethod(targetURL.toString()); // set false as default, addContetInfo can overwrite method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); addContextInfo(method, httpClient, msgContext, targetURL); MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream); } else { requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream); } method.addRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, "" + requestEntity.getContentLength()); ((PostMethod) method).setRequestEntity(requestEntity); } else { method = new GetMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); } String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null) { if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) { method.getParams().setVersion(HttpVersion.HTTP_1_0); } // assume 1.1 } // don't forget the cookies! // Cookies need to be set on HttpState, since HttpMethodBase // overwrites the cookies from HttpState if (msgContext.getMaintainSession()) { HttpState state = httpClient.getState(); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String host = targetURL.getHost(); String path = targetURL.getPath(); boolean secure = targetURL.getProtocol().equals("https"); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure); httpClient.setState(state); } int returnCode = httpClient.executeMethod(method); org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR); String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION); String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { String statusMessage = method.getStatusText(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); try { fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString())); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } finally { method.releaseConnection(); // release connection back to pool. } } // wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method); Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); } else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP message Header[] responseHeaders = method.getResponseHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { if (null == contentLength) { log.debug("\n" + Messages.getMessage("no00", "Content-Length")); } log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) { handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext); } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) { handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext); } } } // always release the connection back to the pool if // it was one way invocation if (msgContext.isPropertyTrue("axis.one.way")) { method.releaseConnection(); } } catch (Exception e) { log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); } }