List of usage examples for org.apache.commons.httpclient HostConfiguration getHost
public String getHost()
From source file:com.liferay.portal.util.HttpImpl.java
public void proxifyState(HttpState httpState, HostConfiguration hostConfiguration) { Credentials proxyCredentials = _proxyCredentials; String host = hostConfiguration.getHost(); if (isProxyHost(host) && (proxyCredentials != null)) { AuthScope scope = new AuthScope(_PROXY_HOST, _PROXY_PORT, null); httpState.setProxyCredentials(scope, proxyCredentials); }/* w ww . j av a 2s . com*/ }
From source file:com.liferay.portal.util.HttpImpl.java
public HostConfiguration getHostConfiguration(String location) throws IOException { if (_log.isDebugEnabled()) { _log.debug("Location is " + location); }/*from ww w. ja va 2 s. c o m*/ HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setHost(new URI(location, false)); if (isProxyHost(hostConfiguration.getHost())) { hostConfiguration.setProxy(_PROXY_HOST, _PROXY_PORT); } HttpConnectionManager httpConnectionManager = _httpClient.getHttpConnectionManager(); HttpConnectionManagerParams httpConnectionManagerParams = httpConnectionManager.getParams(); int defaultMaxConnectionsPerHost = httpConnectionManagerParams.getMaxConnectionsPerHost(hostConfiguration); int maxConnectionsPerHost = GetterUtil.getInteger(PropsUtil.get( HttpImpl.class.getName() + ".max.connections.per.host", new Filter(hostConfiguration.getHost()))); if ((maxConnectionsPerHost > 0) && (maxConnectionsPerHost != defaultMaxConnectionsPerHost)) { httpConnectionManagerParams.setMaxConnectionsPerHost(hostConfiguration, maxConnectionsPerHost); } int timeout = GetterUtil.getInteger( PropsUtil.get(HttpImpl.class.getName() + ".timeout", new Filter(hostConfiguration.getHost()))); if (timeout > 0) { HostParams hostParams = hostConfiguration.getParams(); hostParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, timeout); hostParams.setIntParameter(HttpConnectionParams.SO_TIMEOUT, timeout); } return hostConfiguration; }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
public HttpClient getClient(HostConfiguration hostConfiguration) { if (isProxyHost(hostConfiguration.getHost())) { return _proxyHttpClient; }//from ww w. j a v a2 s.com return _httpClient; }
From source file:com.twinsoft.convertigo.engine.proxy.translated.HttpClient.java
private byte[] getData(HttpConnector connector, String resourceUrl, ParameterShuttle infoShuttle) throws IOException, EngineException { byte[] result = null; try {/*from w w w . j ava2 s . c o m*/ Context context = infoShuttle.context; String proxyServer = Engine.theApp.proxyManager.getProxyServer(); String proxyUser = Engine.theApp.proxyManager.getProxyUser(); String proxyPassword = Engine.theApp.proxyManager.getProxyPassword(); int proxyPort = Engine.theApp.proxyManager.getProxyPort(); HostConfiguration hostConfiguration = connector.hostConfiguration; boolean trustAllServerCertificates = connector.isTrustAllServerCertificates(); // Retrieving httpState getHttpState(connector, infoShuttle); Engine.logEngine.trace("(HttpClient) Retrieving data as a bytes array..."); Engine.logEngine.debug("(HttpClient) Connecting to: " + resourceUrl); // Proxy configuration if (!proxyServer.equals("")) { hostConfiguration.setProxy(proxyServer, proxyPort); Engine.logEngine.debug("(HttpClient) Using proxy: " + proxyServer + ":" + proxyPort); } else { // Remove old proxy configuration hostConfiguration.setProxyHost(null); } Engine.logEngine.debug("(HttpClient) Https: " + connector.isHttps()); CertificateManager certificateManager = connector.certificateManager; URL url = null; String host = ""; int port = -1; if (resourceUrl.toLowerCase().startsWith("https:")) { Engine.logEngine.debug("(HttpClient) Setting up SSL properties"); certificateManager.collectStoreInformation(context); url = new URL(resourceUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port); Engine.logEngine .debug("(HttpClient) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logEngine.debug("(HttpClient) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } resourceUrl = url.getFile(); Engine.logEngine.debug("(HttpClient) Updated URL for SSL purposes: " + resourceUrl); } else { url = new URL(resourceUrl); host = url.getHost(); port = url.getPort(); Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } Engine.logEngine.debug("(HttpClient) Building method on: " + resourceUrl); Engine.logEngine.debug("(HttpClient) postFromUser=" + infoShuttle.postFromUser); Engine.logEngine.debug("(HttpClient) postToSite=" + infoShuttle.postToSite); if (infoShuttle.postFromUser && infoShuttle.postToSite) { method = new PostMethod(resourceUrl); ((PostMethod) method).setRequestEntity( new StringRequestEntity(infoShuttle.userPostData, infoShuttle.userContentType, infoShuttle.context.httpServletRequest.getCharacterEncoding())); } else { method = new GetMethod(resourceUrl); } HttpMethodParams httpMethodParams = method.getParams(); // Cookie configuration if (handleCookie) { Engine.logEngine.debug("(HttpClient) Setting cookie policy."); httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } String basicUser = connector.getAuthUser(); String basicPassword = connector.getAuthPassword(); String givenBasicUser = connector.getGivenAuthUser(); String givenBasicPassword = connector.getGivenAuthPassword(); // Basic authentication configuration String realm = null; if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) { String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser); String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword); httpState.setCredentials(new AuthScope(host, port, realm), new UsernamePasswordCredentials(userName, userPassword)); Engine.logEngine.debug("(HttpClient) Credentials: " + userName + ":******"); } // Setting basic authentication for proxy if (!proxyServer.equals("") && !proxyUser.equals("")) { httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword)); Engine.logEngine.debug("(HttpClient) Proxy credentials: " + proxyUser + ":******"); } // Setting HTTP headers Engine.logEngine.debug("(HttpClient) Incoming HTTP headers:"); String headerName, headerValue; for (int k = 0, kSize = infoShuttle.userHeaderNames.size(); k < kSize; k++) { headerName = (String) infoShuttle.userHeaderNames.get(k); // Cookies are handled by HttpClient, so we do not have to proxy Cookie header // See #986 (Multiples cookies don't work with some proxies) if (headerName.toLowerCase().equals("cookie")) { Engine.logEngine.debug("Cookie header ignored"); } else { headerValue = (String) infoShuttle.userHeaderValues.get(k); method.setRequestHeader(headerName, headerValue); Engine.logEngine.debug(headerName + "=" + headerValue); } } // Getting the result executeMethod(method, connector, resourceUrl, infoShuttle); result = method.getResponseBody(); } finally { if (method != null) method.releaseConnection(); } return result; }
From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * // w ww .ja v a 2s .c o m * @param httpMethodProxyRequest * An object representing the proxy request to be made * @param httpServletResponse * An object by which we can send the proxied response back to * the client * @throws IOException * Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException * Can be thrown to indicate that another error has occurred * @throws EngineException */ private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { try { Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling"); if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) { System.setProperty("javax.net.debug", "all"); Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode"); } else { System.setProperty("javax.net.debug", ""); Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode"); } String baseUrl; String projectName; String connectorName; String contextName; String extraPath; { String requestURI = httpServletRequest.getRequestURI(); Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI); Matcher m = reg_fields.matcher(requestURI); if (m.matches() && m.groupCount() >= 5) { baseUrl = m.group(1); projectName = m.group(2); connectorName = m.group(3); contextName = m.group(4); extraPath = m.group(5); } else { throw new MalformedURLException( "The request doesn't contains needed fields : projectName, connectorName and contextName"); } } String sessionID = httpServletRequest.getSession().getId(); Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : " + extraPath + " ; sessionID : " + sessionID); Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName, connectorName, null); Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName); context.projectName = projectName; context.project = project; ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName); context.connector = proxyHttpConnector; context.connectorName = proxyHttpConnector.getName(); HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration; // Proxy configuration String proxyServer = Engine.theApp.proxyManager.getProxyServer(); String proxyUser = Engine.theApp.proxyManager.getProxyUser(); String proxyPassword = Engine.theApp.proxyManager.getProxyPassword(); int proxyPort = Engine.theApp.proxyManager.getProxyPort(); if (!proxyServer.equals("")) { hostConfiguration.setProxy(proxyServer, proxyPort); Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort); } else { // Remove old proxy configuration hostConfiguration.setProxyHost(null); } String targetHost = proxyHttpConnector.getServer(); Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost); int targetPort = proxyHttpConnector.getPort(); Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort); // Configuration SSL Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps()); CertificateManager certificateManager = proxyHttpConnector.certificateManager; boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates(); if (proxyHttpConnector.isHttps()) { Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties"); certificateManager.collectStoreInformation(context); Engine.logEngine.debug( "(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != targetPort)) { Engine.logEngine .debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, trustAllServerCertificates), targetPort); hostConfiguration.setHost(targetHost, targetPort, myhttps); } Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes"); } else { hostConfiguration.setHost(targetHost, targetPort); } HttpMethod httpMethodProxyRequest; String targetPath = proxyHttpConnector.getBaseDir() + extraPath; // Handle the query string if (httpServletRequest.getQueryString() != null) { targetPath += "?" + httpServletRequest.getQueryString(); } Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath); Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType); if (httpMethodType == HttpMethodType.GET) { // Create a GET request httpMethodProxyRequest = new GetMethod(); } else if (httpMethodType == HttpMethodType.POST) { // Create a standard POST request httpMethodProxyRequest = new PostMethod(); ((PostMethod) httpMethodProxyRequest) .setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream())); } else { throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType); } String charset = httpMethodProxyRequest.getParams().getUriCharset(); URI targetURI; try { targetURI = new URI(targetPath, true, charset); } catch (URIException e) { // Bugfix #1484 String newTargetPath = ""; for (String part : targetPath.split("&")) { if (!newTargetPath.equals("")) { newTargetPath += "&"; } String[] pair = part.split("="); try { newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "=" + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8") : ""); } catch (UnsupportedEncodingException ee) { newTargetPath = targetPath; } } targetURI = new URI(newTargetPath, true, charset); } httpMethodProxyRequest.setURI(targetURI); // Tells the method to automatically handle authentication. httpMethodProxyRequest.setDoAuthentication(true); HttpState httpState = getHttpState(proxyHttpConnector, context); String basicUser = proxyHttpConnector.getAuthUser(); String basicPassword = proxyHttpConnector.getAuthPassword(); String givenBasicUser = proxyHttpConnector.getGivenAuthUser(); String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword(); // Basic authentication configuration String realm = null; if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) { String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser); String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword); httpState.setCredentials(new AuthScope(targetHost, targetPort, realm), new UsernamePasswordCredentials(userName, userPassword)); Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******"); } // Setting basic authentication for proxy if (!proxyServer.equals("") && !proxyUser.equals("")) { httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword)); Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******"); } // Forward the request headers setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector); // Use the CEMS HttpClient HttpClient httpClient = Engine.theApp.httpClient; httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest, httpState); // Check if the proxy response is a redirect // The following code is adapted from // org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that // the // proxied host String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector); httpServletResponse.sendRedirect(redirect); Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")"); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)"); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:"); Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { String headerName = header.getName(); String headerValue = header.getValue(); if (!headerName.equalsIgnoreCase("Transfer-Encoding") && !headerName.equalsIgnoreCase("Set-Cookie")) { httpServletResponse.setHeader(headerName, headerValue); Engine.logEngine.debug(" " + headerName + "=" + headerValue); } } String contentType = null; Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type"); for (Header contentTypeHeader : contentTypeHeaders) { contentType = contentTypeHeader.getValue(); break; } String pageCharset = "UTF-8"; if (contentType != null) { int iCharset = contentType.indexOf("charset="); if (iCharset != -1) { pageCharset = contentType.substring(iCharset + "charset=".length()).trim(); } Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset); } InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream(); // Handle gzipped content Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding"); boolean bGZip = false, bDeflate = false; for (Header contentEncodingHeader : contentEncodingHeaders) { HeaderElement[] els = contentEncodingHeader.getElements(); for (int j = 0; j < els.length; j++) { if ("gzip".equals(els[j].getName())) { Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream"); siteIn = new GZIPInputStream(siteIn); bGZip = true; } else if ("deflate".equals(els[j].getName())) { Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream"); siteIn = new InflaterInputStream(siteIn, new Inflater(true)); bDeflate = true; } } } byte[] bytesDataResult; ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); // String resourceUrl = projectName + targetPath; String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST); try { // Read either from the cache, either from the remote server // InputStream is = proxyCacheManager.getResource(resourceUrl); // if (is != null) { // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache"); // siteIn = is; // } int c = siteIn.read(); while (c > -1) { baos.write(c); c = siteIn.read(); } // if (is != null) is.close(); } finally { context.statistics.stop(t, true); } bytesDataResult = baos.toByteArray(); baos.close(); Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!"); // if (isDynamicContent(httpServletRequest.getPathInfo(), // proxyHttpConnector.getDynamicContentFiles())) { Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content"); bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector, bytesDataResult); String billingClassName = context.getConnector().getBillingClassName(); if (billingClassName != null) { try { Engine.logContext.debug("Billing class name required: " + billingClassName); AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).newInstance(); Engine.logContext.debug("Executing the biller"); biller.insertBilling(context); } catch (Throwable e) { Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage()); } } // } // else { // Engine.logEngine.debug("(ReverseProxyServlet) Static content: " + // contentType); // // // Determine if the resource has already been cached or not // CacheEntry cacheEntry = // proxyCacheManager.getCacheEntry(resourceUrl); // if (cacheEntry instanceof FileCacheEntry) { // FileCacheEntry fileCacheEntry = (FileCacheEntry) cacheEntry; // File file = new File(fileCacheEntry.fileName); // if (!file.exists()) // proxyCacheManager.removeCacheEntry(cacheEntry); // cacheEntry = null; // } // if (cacheEntry == null) { // bytesDataResult = handleStringReplacements(contentType, // proxyHttpConnector, bytesDataResult); // // if (intProxyResponseCode == 200) { // Engine.logEngine.debug("(ReverseProxyServlet) Resource stored: " // + resourceUrl); // cacheEntry = proxyCacheManager.storeResponse(resourceUrl, // bytesDataResult); // cacheEntry.contentLength = bytesDataResult.length; // cacheEntry.contentType = contentType; // Engine.logEngine.debug("(ReverseProxyServlet) Cache entry: " + // cacheEntry); // } // } // } // Send the content to the client if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) { Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset)); } if (bGZip || bDeflate) { baos = new ByteArrayOutputStream(); OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos) : new DeflaterOutputStream(baos, new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true)); compressedOutputStream.write(bytesDataResult); compressedOutputStream.close(); bytesDataResult = baos.toByteArray(); baos.close(); } httpServletResponse.setContentLength(bytesDataResult.length); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); outputStreamClientResponse.write(bytesDataResult); Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission"); } catch (Exception e) { Engine.logEngine.error("Error while trying to proxy page", e); throw new ServletException("Error while trying to proxy page", e); } }
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 * //w w w . j ava 2s.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 www . j a v a 2 s . c om * 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 ww w.j a v a2 s.c o 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//from ww w. jav a2 s . com */ 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")); } }
From source file:org.apache.webdav.lib.WebdavResource.java
/** * Test that the httpURL is the same with the client. * * @return true if the given httpURL is the client for this resource. */// ww w . ja v a 2 s. c o m protected synchronized boolean isTheClient() throws URIException { HostConfiguration hostConfig = client.getHostConfiguration(); Credentials creds = client.getState().getCredentials(null, hostConfig.getHost()); String userName = null; String password = null; if (creds instanceof UsernamePasswordCredentials) { UsernamePasswordCredentials upc = (UsernamePasswordCredentials) creds; userName = upc.getUserName(); password = upc.getPassword(); } String ref = httpURL.getUser(); boolean userMatches = userName != null ? userName.equals(ref) : ref == null; if (userMatches) { ref = httpURL.getPassword(); userMatches = password != null ? password.equals(ref) : ref == null; } else { return false; } if (userMatches) { return httpURL.getHost().equalsIgnoreCase(hostConfig.getHost()) && httpURL.getPort() == hostConfig.getProtocol().resolvePort(hostConfig.getPort()); } return false; }