List of usage examples for org.apache.commons.httpclient HttpMethodBase getStatusText
@Override
public String getStatusText()
From source file:com.cloud.network.nicira.NiciraNvpApi.java
private String responseToErrorMessage(HttpMethodBase method) { assert method.isRequestSent() : "no use getting an error message unless the request is sent"; if ("text/html".equals(method.getResponseHeader("Content-Type").getValue())) { // The error message is the response content // Safety margin of 1024 characters, anything longer is probably useless // and will clutter the logs try {/*ww w . j a va 2 s . co m*/ return method.getResponseBodyAsString(1024); } catch (IOException e) { s_logger.debug("Error while loading response body", e); } } // The default return method.getStatusText(); }
From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java
public int logout() { log.finest("Logout"); try {// w w w . j a va 2 s . com log.finest("URI:" + url.toURI().toString()); } catch (URISyntaxException ex) { log.finest("Logout URISyntaxException " + ex.getMessage()); } String logoutUrl = this.url.toString() + contextRoot + JAZZ_LOGOUT_URL; log.finest("Attempting to log out with this url: " + logoutUrl); HttpMethodBase authenticationMethod = new PostMethod(this.url.toString() + contextRoot + JAZZ_LOGOUT_URL); authenticationMethod.setFollowRedirects(false); UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) super.getState() .getCredentials(new AuthScope(host, port)); if (null != credentials && !(credentials.getUserName().isEmpty() && credentials.getPassword().isEmpty())) { log.finest(String.format("Adding authorizationheadder for logout for user: %s", credentials.getUserName())); authenticationMethod.addRequestHeader("Authorization:", "Base " + credentials.getUserName() + ":" + credentials.getPassword()); } String body = ""; String status = ""; int responseCode = 0; ; try { responseCode = executeMethod(authenticationMethod); body = authenticationMethod.getResponseBodyAsString(); status = authenticationMethod.getStatusText(); log.finest(String.format("Response code %s, Status text %s", responseCode, status)); } catch (Exception e) { log.log(Level.SEVERE, "Failed to log out!", e); log.log(Level.SEVERE, body); } return responseCode; }
From source file:com.springsource.hq.plugin.tcserver.cli.client.configuration.FileResponseHandler.java
public T handleResponse(int responseCode, HttpMethodBase method) throws IOException { switch (responseCode) { case 200://from ww w. j a v a 2s. co m FileOutputStream fileOutputStream = null; InputStream in = method.getResponseBodyAsStream(); try { fileOutputStream = new FileOutputStream(targetFile.getAbsolutePath()); final byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { fileOutputStream.write(buf, 0, len); } return getSuccessResponse(); } catch (Exception e) { return getErrorResponse(createServiceError("UnexpectedError", "Unable to deserialize result")); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { } } } case 401: // Unauthorized return getErrorResponse( createServiceError("LoginFailure", "The given username and password could not be validated")); default: String reasonText; if (method.getStatusText() != null) { reasonText = method.getStatusText(); } else { reasonText = "An unexpected error occurred"; } return getErrorResponse(createServiceError("UnexpectedError", reasonText)); } }
From source file:de.laeubisoft.tools.ant.validation.W3CCSSValidationTask.java
/** * Creates the actual request to the validation server for a given * {@link URL} and returns an inputstream the result can be read from * /*from w w w .j av a2s .co m*/ * @param uriToCheck * the URL to check (or <code>null</code> if text or file should * be used as input * @return the stream to read the response from * @throws IOException * if unrecoverable communication error occurs * @throws BuildException * if server returned unexspected results */ private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT)); if (uriToCheck != null) { params.add(new NameValuePair("uri", uriToCheck.toString())); } else { if (text != null) { params.add(new NameValuePair("text", text)); } } if (usermedium != null) { params.add(new NameValuePair("usermedium", usermedium)); } if (profile != null) { params.add(new NameValuePair("profile", profile)); } if (lang != null) { params.add(new NameValuePair("lang", lang)); } if (warning != null) { params.add(new NameValuePair("warning", warning)); } HttpClient httpClient = new HttpClient(); HttpMethodBase method; if (uriToCheck != null) { //URIs must be checked via traditonal GET... GetMethod getMethod = new GetMethod(validator); getMethod.setQueryString(params.toArray(new NameValuePair[0])); method = getMethod; } else { PostMethod postMethod = new PostMethod(validator); if (text != null) { //Text request must be multipart encoded too... postMethod.setRequestEntity(new MultipartRequestEntity(Tools.nvToParts(params).toArray(new Part[0]), postMethod.getParams())); } else { //Finally files must be checked with multipart-forms.... postMethod.setRequestEntity( Tools.createFileUpload(file, "file", null, params, postMethod.getParams())); } method = postMethod; } int result = httpClient.executeMethod(method); if (result == HttpStatus.SC_OK) { return method.getResponseBodyAsStream(); } else { throw new BuildException("Server returned " + result + " " + method.getStatusText()); } }
From source file:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java
/** * Creates the actual request to the validation server for a given * {@link URL} and returns an inputstream the result can be read from * /*from ww w. j a va2 s .c o m*/ * @param uriToCheck * the URL to check * @return the stream to read the response from * @throws IOException * if unrecoverable communication error occurs * @throws BuildException * if server returned unexspected results */ private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT)); if (uriToCheck != null) { params.add(new NameValuePair("uri", uriToCheck.toString())); } else { if (fragment != null) { params.add(new NameValuePair("fragment", fragment)); } } if (debug) { params.add(new NameValuePair("debug", "1")); } if (charset != null) { params.add(new NameValuePair("charset", charset)); } if (doctype != null) { params.add(new NameValuePair("doctype", doctype)); } HttpClient httpClient = new HttpClient(); HttpMethodBase method; if (uriToCheck != null) { //URIs must be checked wia traditonal GET... GetMethod getMethod = new GetMethod(validator); getMethod.setQueryString(params.toArray(new NameValuePair[0])); method = getMethod; } else { PostMethod postMethod = new PostMethod(validator); if (fragment != null) { //Fragment request can be checked via FORM Submission postMethod.addParameters(params.toArray(new NameValuePair[0])); } else { //Finally files must be checked with multipart-forms.... postMethod.setRequestEntity(Tools.createFileUpload(uploaded_file, "uploaded_file", charset, params, postMethod.getParams())); } method = postMethod; } int result = httpClient.executeMethod(method); if (result == HttpStatus.SC_OK) { return method.getResponseBodyAsStream(); } else { throw new BuildException("Server returned " + result + " " + method.getStatusText()); } }
From source file:com.atlantbh.jmeter.plugins.oauth.OAuthSampler.java
@Override public SampleResult sample() { HttpMethodBase httpMethod = null; HttpClient client = null;/* ww w . j av a 2s . c o m*/ InputStream instream = null; SampleResult res = new SampleResult(); try { res.setSuccessful(false); res.setResponseCode("000"); res.setSampleLabel(getName()); res.setURL(getUrl()); res.setDataEncoding("UTF-8"); res.setDataType("text/xml"); res.setSamplerData(getRequestBody()); res.setMonitor(isMonitor()); res.sampleStart(); String urlStr = getUrl().toString(); log.debug("Start : sample " + urlStr); log.debug("method " + getMethod()); httpMethod = createHttpMethod(getMethod(), urlStr); setDefaultRequestHeaders(httpMethod); client = setupConnection(getUrl(), httpMethod); if (httpMethod instanceof EntityEnclosingMethod) { ((EntityEnclosingMethod) httpMethod) .setRequestEntity(new StringRequestEntity(getRequestBody(), "text/xml", "UTF-8")); } overrideHeaders(httpMethod, urlStr, getMethod()); res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = -1; try { statusCode = client.executeMethod(httpMethod); } catch (RuntimeException e) { log.error("Exception when executing '" + httpMethod + "'", e); throw e; } instream = httpMethod.getResponseBodyAsStream(); if (instream != null) { Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null) { ct = h.getValue(); res.setContentType(ct); res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(httpMethod); res.setResponseHeaders(responseHeaders); log.debug("End : sample"); httpMethod.releaseConnection(); return res; } catch (MalformedURLException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IllegalArgumentException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IOException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); return res; } } }
From source file:com.snaker.DownloadManager.java
private Runnable createRunnable(final Downloader d) { final Task task = d.getTask(); return new Runnable() { @Override//from w w w . j a va 2s. c o m public void run() { logger.info("start download:" + d.getUrl()); HttpClient client = clients.get(task.getId()); DownloadHandler handler = d.getHandler(); HttpMethodBase m = null; d.setStatus(Status.STARTED); d.setStartTime(System.currentTimeMillis()); try { String url = d.getUrl(); if (d.isGet()) { GetMethod get = new GetMethod(url); m = get; } else { final String requestCharset = d.getRequestCharset(); PostMethod post = new PostMethod(url) { public String getRequestCharSet() { if (requestCharset != null) return requestCharset; else return super.getRequestCharSet(); } public boolean getFollowRedirects() { return d.isFollowRedirects(); } }; if (requestCharset != null) { post.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=" + requestCharset); } DownloadParams parms = d.getParms(); if (parms != null) post.setRequestBody(parms.toNVP()); m = post; } { // set the headers m.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1"); m.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); m.setRequestHeader("Accept-Language", "en-us,zh-cn;q=0.5"); m.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); m.setRequestHeader("Referer", url); } client.executeMethod(m); //check status int sc = m.getStatusCode(); d.setStatusCode(sc); if (isBadStatusCode(sc)) { logger.error("download failed,url:" + d.getUrl() + ",Status Code:" + sc); d.setStatus(Status.FAILED); d.setDescription(m.getStatusText()); return; } else if (sc == 404 || sc == 410) { d.setStatus(Status.FINISHED); d.setDescription("NOT FOUND"); return; } long size = m.getResponseContentLength(); d.setFileSize(size); // get File Name if (d.getFileName() == null) { Header h = m.getResponseHeader("Content-Disposition"); String fileName = null; if (h != null) { String f = h.getValue(); int tag = f.indexOf("filename="); if (tag != -1 && tag != f.length() - 1) fileName = f.substring(tag + 1); } if (fileName == null || fileName.length() == 0) { int tag1 = url.lastIndexOf("/"); int tag2 = url.lastIndexOf("?"); if (tag1 != -1 && tag1 != url.length() - 1) { if (tag2 > tag1) { fileName = url.substring(tag1 + 1, tag2); } else { fileName = url.substring(tag1 + 1); } } } d.setFileName(fileName); } // set the all headers Header[] headers = m.getResponseHeaders(); if (headers != null) { for (Header header : headers) { d.addResponseHeader(header.getName(), header.getValue()); } } d.setStatus(Status.RUNNING); // recv the body if (handler == null) { byte[] content = m.getResponseBody(); int len = content.length; d.setFileSize(len); d.setReceived(len); d.setResponseCharset(m.getResponseCharSet()); d.setResponseBody(content); } else { InputStream is = m.getResponseBodyAsStream(); handler.start(d); byte[] buffer = new byte[102400]; long count = 0; while (true) { int r = is.read(buffer); if (r > 0) { count += r; d.setReceived(count); handler.handle(buffer, r); } else { break; } } is.close(); } d.setStatus(Status.FINISHED); } catch (Exception e) { logger.error("download failed,url:" + d.getUrl(), e); d.setStatus(Status.FAILED); d.setDescription(e.getMessage()); } finally { m.releaseConnection(); if (handler != null) { handler.stop(); } downloadings.remove(d); d.setEndTime(System.currentTimeMillis()); while (downloaded.size() >= maxDownloadedCount) { downloaded.poll(); } downloaded.offer(d); task.downloadFininshed(d); } } }; }
From source file:com.atlantbh.jmeter.plugins.rest.RestSampler.java
/** * Method invoked by JMeter when a sample needs to happen. It's actually an * indirect call from the main sampler interface. it's resolved in the base * class./*ww w . ja v a 2s. c o m*/ * * This is a copy and paste from the HTTPSampler2 - quick and dirty hack as * that class is not very extensible. The reason to extend and slightly * modify is that I needed to get the body content from a text field in the * GUI rather than a file. */ public SampleResult sample() { HttpMethodBase httpMethod = null; HttpClient client = null; InputStream instream = null; SampleResult res = new SampleResult(); try { res.setSuccessful(false); res.setResponseCode("000"); res.setSampleLabel(getName()); res.setURL(getUrl()); res.setDataEncoding("UTF-8"); res.setDataType("text/xml"); res.setMonitor(isMonitor()); res.sampleStart(); String urlStr = getUrl().toString(); String request = getMethod().toString() + " " + urlStr + "\n"; request += getRequestBody().toString(); res.setSamplerData(request); log.debug("Start : sample " + urlStr); log.debug("method " + getMethod()); httpMethod = createHttpMethod(getMethod(), urlStr); // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(getUrl(), httpMethod); // Handle the various methods if (httpMethod instanceof EntityEnclosingMethod) { ((EntityEnclosingMethod) httpMethod) .setRequestEntity(new StringRequestEntity(getRequestBody(), "text/xml", "UTF-8")); //res.setQueryString(getRequestBody()); //String postBody = sendData((EntityEnclosingMethod) httpMethod); //res.setResponseData(postBody.getBytes()); //String postBody = ""; //try { postBody = Base64Util.processStargateRequest(getRequestBody());} //catch (Exception e) {postBody =getRequestBody(); e.printStackTrace();} // //res.setSamplerData(/*res.getSamplerData() + "\r\n*/"ORIGINAL CONTENT:\r\n\r\n" + getRequestBody() + "\r\n\r\nSENT CONTENT:\r\n\r\n" + postBody); } overrideHeaders(httpMethod); res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = -1; try { statusCode = client.executeMethod(httpMethod); } catch (RuntimeException e) { log.error("Exception when executing '" + httpMethod + "'", e); throw e; } // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } //if (res.getResponseDataAsString().length() != 0) // try{ // String response = Base64Util.processStargateResponse(res.getResponseDataAsString()); // res.setResponseData(response); // } catch (Exception e) // { // log.error(e.getMessage()); // } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: // res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(httpMethod); res.setResponseHeaders(responseHeaders); /*if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but // avoids NPE throw new IllegalArgumentException("Missing location header"); } res.setRedirectLocation(headerLocation.getValue()); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); */ log.debug("End : sample"); httpMethod.releaseConnection(); return res; } catch (MalformedURLException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); //SampleResult err = errorResult(e, res); //err.setSampleLabel("Error: " + url.toString()); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } catch (IOException e) { res.sampleEnd(); log.warn(e.getMessage()); res.setResponseMessage(e.getMessage()); return res; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); return res; } } }
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 * /* ww w.ja v a 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:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and then * reads the response SOAP message back from the SOAP server * * @param msgContext the messsage context * * @throws AxisFault//from www .j a v a 2 s .c om */ public void invoke(MessageContext msgContext) throws AxisFault { //test(); HttpMethodBase method = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); } try { URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); // no need to retain these, as the cookies/credentials are // stored in the message context across multiple requests. // the underlying connection manager, however, is retained // so sockets get recycled when possible. //org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG); HttpClient httpClient = new HttpClient(this.connectionManager); // the timeout value for allocation of connections from the pool httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout()); HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL); boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) { posting = webMethod.equals(HTTPConstants.HEADER_POST); } } if (posting) { Message reqMessage = msgContext.getRequestMessage(); method = new PostMethod(targetURL.toString()); // set false as default, addContetInfo can overwrite method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); addContextInfo(method, httpClient, msgContext, targetURL); MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream); } else { requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream); } method.addRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, "" + requestEntity.getContentLength()); ((PostMethod) method).setRequestEntity(requestEntity); } else { method = new GetMethod(targetURL.toString()); addContextInfo(method, httpClient, msgContext, targetURL); } String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null) { if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) { method.getParams().setVersion(HttpVersion.HTTP_1_0); } // assume 1.1 } // don't forget the cookies! // Cookies need to be set on HttpState, since HttpMethodBase // overwrites the cookies from HttpState if (msgContext.getMaintainSession()) { HttpState state = httpClient.getState(); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String host = targetURL.getHost(); String path = targetURL.getPath(); boolean secure = targetURL.getProtocol().equals("https"); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure); fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure); httpClient.setState(state); } int returnCode = httpClient.executeMethod(method); org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR); String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION); String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { String statusMessage = method.getStatusText(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); try { fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString())); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } finally { method.releaseConnection(); // release connection back to pool. } } // wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method); Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); } else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP message Header[] responseHeaders = method.getResponseHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { if (null == contentLength) { log.debug("\n" + Messages.getMessage("no00", "Content-Length")); } log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) { handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext); } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) { handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext); } } } // always release the connection back to the pool if // it was one way invocation if (msgContext.isPropertyTrue("axis.one.way")) { method.releaseConnection(); } } catch (Exception e) { log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); } }