List of usage examples for org.apache.commons.httpclient HostConfiguration getProtocol
public Protocol getProtocol()
From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java
/** * rewrite request method//from ww w. j a v a 2 s . co m * @param method * @return * @throws MalformedURLException */ private static HttpMethod rewrite(HttpMethod method) throws MalformedURLException { org.apache.commons.httpclient.Header location = method.getResponseHeader("location"); if (location == null) return method; HostConfiguration config = method.getHostConfiguration(); URL url; try { url = new URL(location.getValue()); } catch (MalformedURLException e) { url = new URL(config.getProtocol().getScheme(), config.getHost(), config.getPort(), mergePath(method.getPath(), location.getValue())); } method = clone(method, url); return method; }
From source file:au.edu.monash.merc.capture.util.httpclient.ssl.HttpHostFactory.java
/** * Get a Protocol for the given parameters. The default implementation selects a protocol based only on the scheme. * Subclasses can do fancier things, such as select SSL parameters based on the host or port. This method must not * return null.//www . j ava 2 s . c o m */ protected Protocol getProtocol(HostConfiguration old, String scheme, String host, int port) { final Protocol oldProtocol = old.getProtocol(); if (oldProtocol != null) { final String oldScheme = oldProtocol.getScheme(); if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) { // The old protocol has the desired scheme. return oldProtocol; // Retain it. } } Protocol newProtocol = (scheme != null && scheme.toLowerCase().endsWith("s")) ? httpsProtocol : httpProtocol; if (newProtocol == null) { newProtocol = Protocol.getProtocol(scheme); } return newProtocol; }
From source file:lucee.commons.net.http.httpclient3.HTTPResponse3Impl.java
@Override public URL getURL() { HostConfiguration config = rsp.getHostConfiguration(); try {//w w w. ja v a2 s.c om String qs = rsp.getQueryString(); if (StringUtil.isEmpty(qs)) return new URL(config.getProtocol().getScheme(), config.getHost(), config.getPort(), rsp.getPath()); return new URL(config.getProtocol().getScheme(), config.getHost(), config.getPort(), rsp.getPath() + "?" + qs); } catch (MalformedURLException e) { } return url; }
From source file:ch.cyberduck.core.dav.DAVResource.java
/** * Overwritten to make sure the client and its properties are not overwritten when * the credentials change. See #2974./*from w w w. j a va 2 s.com*/ * * @return true if the given httpURL is the client for this resource. */ @Override protected synchronized boolean isTheClient() throws URIException { final HostConfiguration hostConfig = client.getHostConfiguration(); // Hack to enable preemptive authentication client.getState().setCredentials(null, httpURL.getHost(), hostCredentials); return httpURL.getHost().equalsIgnoreCase(hostConfig.getHost()) && httpURL.getPort() == hostConfig.getProtocol().resolvePort(hostConfig.getPort()); }
From source file:com.legstar.http.client.CicsHttpTest.java
/** * Try to create a host configuration.//ww w. j av a 2 s .com */ public void testCreateHostConfiguration() { CicsHttp cicsHttp = new CicsHttp(getName(), getEndpoint()); HostConfiguration hostConfiguration = cicsHttp.createHostConfiguration(getEndpoint()); assertEquals("mainframe", hostConfiguration.getHost()); assertEquals("http://mainframe:3080", hostConfiguration.getHostURL()); assertEquals(3080, hostConfiguration.getPort()); assertEquals("http:80", hostConfiguration.getProtocol().toString()); }
From source file:com.cyberway.issue.httpclient.ThreadLocalHttpConnectionManager.java
/** * @see HttpConnectionManager#getConnectionWithTimeout(HostConfiguration, long) * /*from ww w.j a v a 2 s . c o m*/ * @since 3.0 */ public HttpConnection getConnectionWithTimeout(final HostConfiguration hostConfiguration, final long timeout) { final ConnectionInfo ci = getConnectionInfo(); HttpConnection httpConnection = ci.conn; // make sure the host and proxy are correct for this connection // close it and set the values if they are not if (httpConnection == null || !finishLastResponse(httpConnection) || !hostConfiguration.hostEquals(httpConnection) || !hostConfiguration.proxyEquals(httpConnection)) { if (httpConnection != null && httpConnection.isOpen()) { closer.closeConnection(httpConnection); } httpConnection = new HttpConnection(hostConfiguration); httpConnection.setHttpConnectionManager(this); httpConnection.getParams().setDefaults(this.params); ci.conn = httpConnection; httpConnection.setHost(hostConfiguration.getHost()); httpConnection.setPort(hostConfiguration.getPort()); httpConnection.setProtocol(hostConfiguration.getProtocol()); httpConnection.setLocalAddress(hostConfiguration.getLocalAddress()); httpConnection.setProxyHost(hostConfiguration.getProxyHost()); httpConnection.setProxyPort(hostConfiguration.getProxyPort()); } // remove the connection from the timeout handler ci.idleStartTime = Long.MAX_VALUE; return httpConnection; }
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 ww w .j a v a 2 s. com*/ * @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 .j ava 2s . c o 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:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.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 message context * * @throws AxisFault//from w w w . jav a 2 s .co m * @deprecated */ public void invoke(MessageContext msgContext) throws AxisFault { HttpMethodBase method = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("enter00", //$NON-NLS-1$ "CommonsHTTPSender::invoke")); //$NON-NLS-1$ } 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(connectionManager); // the timeout value for allocation of connections from the pool httpClient.setHttpConnectionFactoryTimeout(clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, targetURL); httpClient.setHostConfiguration(hostConfiguration); // look for option to send credentials preemptively (w/out challenge) // Control of Preemptive is controlled via policy on a per call basis. String preemptive = (String) msgContext.getProperty("HTTPPreemptive"); //$NON-NLS-1$ if ("true".equals(preemptive)) //$NON-NLS-1$ { httpClient.getParams().setAuthenticationPreemptive(true); } String webMethod = null; 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) { webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) { posting = webMethod.equals(HTTPConstants.HEADER_POST); } } Message reqMessage = msgContext.getRequestMessage(); if (posting) { method = new PostMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); ByteArrayOutputStream baos = new ByteArrayOutputStream(); reqMessage.writeTo(baos); ((PostMethod) method).setRequestBody(new ByteArrayInputStream(baos.toByteArray())); ((PostMethod) method).setUseExpectHeader(false); // workaround for } else { method = new GetMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); } // 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(); state.setCookiePolicy(CookiePolicy.COMPATIBILITY); String host = hostConfiguration.getHost(); String path = targetURL.getPath(); boolean secure = hostConfiguration.getProtocol().isSecure(); String ck1 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE); String ck2 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE2); if (ck1 != null) { int index = ck1.indexOf('='); state.addCookie(new Cookie(host, ck1.substring(0, index), ck1.substring(index + 1), path, null, secure)); } if (ck2 != null) { int index = ck2.indexOf('='); state.addCookie(new Cookie(host, ck2.substring(0, index), ck2.substring(index + 1), path, null, secure)); } httpClient.setState(state); } boolean hasSoapFault = false; int returnCode = httpClient.executeMethod(method); String contentType = null; String contentLocation = null; String contentLength = null; if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) { contentType = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(); } if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION) != null) { contentLocation = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION).getValue(); } if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH) != null) { contentLength = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH).getValue(); } contentType = (null == contentType) ? null : contentType.trim(); 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") //$NON-NLS-1$ && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through hasSoapFault = true; } else { String statusMessage = method.getStatusText(); AxisFault fault = new AxisFault("HTTP", //$NON-NLS-1$ "(" + returnCode + ")" //$NON-NLS-1$ //$NON-NLS-2$ + statusMessage, null, null); try { fault.setFaultDetailString(Messages.getMessage("return01", //$NON-NLS-1$ "" + returnCode, method.getResponseBodyAsString())); //$NON-NLS-1$ 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); 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()); } OperationDesc operation = msgContext.getOperation(); if (hasSoapFault || operation.getMep().equals(OperationType.REQUEST_RESPONSE)) { msgContext.setResponseMessage(outMsg); } else { // Change #1 // // If the operation is a one-way, then don't set the response // on the msg context. Doing so will cause Axis to attempt to // read from a non-existent SOAP message which causes errors. // // Note: also checking to see if the return type is our "VOID" // QName from the AeInvokeHandler since that's our workaround // for avoiding Axis's Thread creation in Call.invokeOneWay() // // Since the message context won't have a chance to consume the // response stream (which closes the connection), close the // connection here. method.releaseConnection(); } if (log.isDebugEnabled()) { if (null == contentLength) { log.debug("\n" //$NON-NLS-1$ + Messages.getMessage("no00", "Content-Length")); //$NON-NLS-1$ //$NON-NLS-2$ } log.debug("\n" + Messages.getMessage("xmlRecd00")); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("-----------------------------------------------"); //$NON-NLS-1$ 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)) msgContext.setProperty(HTTPConstants.HEADER_COOKIE, cleanupCookie(headers[i].getValue())); else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) msgContext.setProperty(HTTPConstants.HEADER_COOKIE2, cleanupCookie(headers[i].getValue())); } } } catch (Throwable t) { log.debug(t); if (method != null) { method.releaseConnection(); } // We can call Axis.makeFault() if it's an exception; otherwise // construct the AxisFault directly. throw (t instanceof Exception) ? AxisFault.makeFault((Exception) t) : new AxisFault(t.getLocalizedMessage(), t); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", //$NON-NLS-1$ "CommonsHTTPSender::invoke")); //$NON-NLS-1$ } }
From source file:org.apache.axis.transport.http.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//w ww .j a v a 2 s . c o m */ 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()); 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")); } }