List of usage examples for org.apache.commons.httpclient HttpMethodBase getStatusCode
@Override public int getStatusCode()
From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java
/** * This is the main method that does the authentication and should be * invoked by the classes that would like to open a new authentication * process against an HTTP Basic protected source. * <p>//from w w w.ja v a 2 s . co m * The username and password for the source are assumed to be the ones * captured during the authentication. These are stored in creds and in * this case the root parameters. creds is an array of credentials for * all external sources. The first element is 'root' which contains the * credentials captured from the login page. This method reviews if there * is a credential id identical to the name associated to this module * in the config file. If so, these credentials are used to authenticate * against this HTTP Basic source, and if not 'root' one will be used * instead. * <p> * If the HTTP Basic authentication result is OK, it creates an * authentication cookie containing the HTTP Basic credentials * to be reused during authorization. The content returned back from the * remote secure backend system is sent as well. Anyway, the HTTP * response code is returned in this method to inform the caller on the * status. * * @param request HTTP request * @param response HTTP response * @param authCookies vector that contains the authentication cookies * @param url the document url * @param creds an array of credentials for all external sources * @param id the default credential id to be retrieved from creds * @return the HTTP error code * @throws HttpException * @throws IOException */ public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies, String url, Credentials creds, String id) throws HttpException, IOException { Cookie[] cookies = null; //Credentials UsernamePasswordCredentials credentials = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); // Debug logger.debug("HTTP Basic authentication start"); //First read the u/p the credentails store, in this case using the same as the root login logger.debug("HttpBasic: trying to get creds from repository ID: " + id); Credential httpBasicCred = null; try { httpBasicCred = creds.getCredential(id); } catch (NullPointerException npe) { logger.error("NPE while reading credentials of ID: " + id); } if (httpBasicCred != null) { credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } else { logger.debug("HttpBasic: trying to get creds from repository \"root\""); httpBasicCred = creds.getCredential("root"); if (httpBasicCred != null) { logger.info("Trying with root credentails"); credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } } logger.debug("Authenticating"); Header[] headers = null; HttpMethodBase method = null; //Get Max connections int maxConnectionsPerHost = 30; int maxTotalConnections = 100; //Cookie Max Age int authMaxAge = -1; try { maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue(); maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue(); authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge()); } catch (NumberFormatException nfe) { logger.error( "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:"); logger.error(" * maxConnectionsPerHost * maxTotalConnections * authMaxAge"); } // Protection if (webProcessor == null) { // Instantiate Web processor if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) { webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections); } else { webProcessor = new WebProcessor(); } } // // Launch the authentication process // // A fixed URL in the repository that all users have access to which can be used to authN a user // and capture the HTTP Authorization Header String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage"); try { // Set HTTP headers headers = new Header[1]; // Set User-Agent headers[0] = new Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5"); // Request page, testing if credentials are valid if (credentials != null) { logger.debug("Username: " + credentials.getUserName()); logger.debug("URL: " + authURL); } //HTTP request method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL); //Read the auth header and store in the cookie, the authZ class will use this later headers = method.getRequestHeaders(); Header authHeader = null; authHeader = method.getRequestHeader("Authorization"); // Cache status code if (method != null) statusCode = method.getStatusCode(); if (statusCode == HttpServletResponse.SC_OK) { //Authentication worked, so create the auth cookie to indicate it has worked Cookie extAuthCookie = null; extAuthCookie = new Cookie(BASIC_COOKIE, ""); if (authHeader != null) { String basicCookie = null; try { basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder); if (basicCookie == null) { basicCookie = ""; } } catch (Exception ex) { logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex); basicCookie = ""; } extAuthCookie.setValue(basicCookie); } String authCookieDomain = null; String authCookiePath = null; // Cache cookie properties authCookieDomain = valveConf.getAuthCookieDomain(); authCookiePath = valveConf.getAuthCookiePath(); // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info if (logger.isDebugEnabled()) logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); //sendCookies support boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()) .booleanValue(); boolean sendCookies = false; if (isSessionEnabled) { sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue(); } if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) { logger.debug("Adding cookie to response"); response.addCookie(extAuthCookie); } //Add cookies to the Cookie array to support sessions authCookies.add(extAuthCookie); logger.debug("Cookie added to the array"); } // Clear webProcessor cookies webProcessor.clearCookies(); } catch (Exception e) { // Log error logger.error("HTTP Basic authentication failure: " + e.getMessage(), e); // Garbagge collect method = null; // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // End of the authentication process logger.debug("HTTP Basic Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:com.sun.syndication.propono.atom.client.OAuthStrategy.java
private void callOAuthUri(String uri) throws ProponoException { final HttpClient httpClient = new HttpClient(); final HttpMethodBase method; final String content; Map<String, String> params = new HashMap<String, String>(); if (params == null) { params = new HashMap<String, String>(); }//from w ww . j ava2 s .c o m params.put("oauth_version", "1.0"); if (username != null) { params.put("xoauth_requestor_id", username); } params.put("oauth_consumer_key", consumerKey); params.put("oauth_signature_method", keyType); params.put("oauth_timestamp", Long.toString(timestamp)); params.put("oauth_nonce", nonce); params.put("oauth_callback", "none"); OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl); OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider); OAuthAccessor accessor = new OAuthAccessor(consumer); if (state == State.UNAUTHORIZED) { try { OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet()); message.sign(accessor); String finalUri = OAuth.addParameters(message.URL, message.getParameters()); method = new GetMethod(finalUri); httpClient.executeMethod(method); content = method.getResponseBodyAsString(); } catch (Exception e) { throw new ProponoException("ERROR fetching request token", e); } } else if (state == State.REQUEST_TOKEN) { try { params.put("oauth_token", requestToken); params.put("oauth_token_secret", tokenSecret); accessor.tokenSecret = tokenSecret; OAuthMessage message = new OAuthMessage("POST", uri, params.entrySet()); message.sign(accessor); String finalUri = OAuth.addParameters(message.URL, message.getParameters()); method = new PostMethod(finalUri); httpClient.executeMethod(method); content = method.getResponseBodyAsString(); } catch (Exception e) { throw new ProponoException("ERROR fetching request token", e); } } else if (state == State.AUTHORIZED) { try { params.put("oauth_token", accessToken); params.put("oauth_token_secret", tokenSecret); accessor.tokenSecret = tokenSecret; OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet()); message.sign(accessor); String finalUri = OAuth.addParameters(message.URL, message.getParameters()); method = new GetMethod(finalUri); httpClient.executeMethod(method); content = method.getResponseBodyAsString(); } catch (Exception e) { throw new ProponoException("ERROR fetching request token", e); } } else { method = null; content = null; return; } String token = null; String secret = null; if (content != null) { String[] settings = content.split("&"); for (int i = 0; i < settings.length; i++) { String[] setting = settings[i].split("="); if (setting.length > 1) { if ("oauth_token".equals(setting[0])) { token = setting[1]; } else if ("oauth_token_secret".equals(setting[0])) { secret = setting[1]; } } } } switch (state) { case UNAUTHORIZED: if (token != null && secret != null) { requestToken = token; tokenSecret = secret; state = State.REQUEST_TOKEN; } else { throw new ProponoException("ERROR: requestToken or tokenSecret is null"); } break; case REQUEST_TOKEN: if (method.getStatusCode() == 200) { state = State.AUTHORIZED; } else { throw new ProponoException("ERROR: authorization returned code: " + method.getStatusCode()); } break; case AUTHORIZED: if (token != null && secret != null) { accessToken = token; tokenSecret = secret; state = State.ACCESS_TOKEN; } else { throw new ProponoException("ERROR: accessToken or tokenSecret is null"); } break; } }
From source file:com.rometools.propono.atom.client.OAuthStrategy.java
private void callOAuthUri(final String uri) throws ProponoException { final HttpClient httpClient = new HttpClient(); final HttpMethodBase method; final String content; final Map<String, String> params = new HashMap<String, String>(); params.put("oauth_version", "1.0"); if (username != null) { params.put("xoauth_requestor_id", username); }// w ww.j a va2 s . c o m params.put("oauth_consumer_key", consumerKey); params.put("oauth_signature_method", keyType); params.put("oauth_timestamp", Long.toString(timestamp)); params.put("oauth_nonce", nonce); params.put("oauth_callback", "none"); final OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl); final OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider); final OAuthAccessor accessor = new OAuthAccessor(consumer); if (state == State.UNAUTHORIZED) { try { final OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet()); message.sign(accessor); final String finalUri = OAuth.addParameters(message.URL, message.getParameters()); method = new GetMethod(finalUri); httpClient.executeMethod(method); content = method.getResponseBodyAsString(); } catch (final Exception e) { throw new ProponoException("ERROR fetching request token", e); } } else if (state == State.REQUEST_TOKEN) { try { params.put("oauth_token", requestToken); params.put("oauth_token_secret", tokenSecret); accessor.tokenSecret = tokenSecret; final OAuthMessage message = new OAuthMessage("POST", uri, params.entrySet()); message.sign(accessor); final String finalUri = OAuth.addParameters(message.URL, message.getParameters()); method = new PostMethod(finalUri); httpClient.executeMethod(method); content = method.getResponseBodyAsString(); } catch (final Exception e) { throw new ProponoException("ERROR fetching request token", e); } } else if (state == State.AUTHORIZED) { try { params.put("oauth_token", accessToken); params.put("oauth_token_secret", tokenSecret); accessor.tokenSecret = tokenSecret; final OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet()); message.sign(accessor); final String finalUri = OAuth.addParameters(message.URL, message.getParameters()); method = new GetMethod(finalUri); httpClient.executeMethod(method); content = method.getResponseBodyAsString(); } catch (final Exception e) { throw new ProponoException("ERROR fetching request token", e); } } else { method = null; content = null; return; } String token = null; String secret = null; if (content != null) { final String[] settings = content.split("&"); for (final String setting2 : settings) { final String[] setting = setting2.split("="); if (setting.length > 1) { if ("oauth_token".equals(setting[0])) { token = setting[1]; } else if ("oauth_token_secret".equals(setting[0])) { secret = setting[1]; } } } } // TODO review switch without 'default' switch (state) { case UNAUTHORIZED: if (token != null && secret != null) { requestToken = token; tokenSecret = secret; state = State.REQUEST_TOKEN; } else { throw new ProponoException("ERROR: requestToken or tokenSecret is null"); } break; case REQUEST_TOKEN: if (method.getStatusCode() == 200) { state = State.AUTHORIZED; } else { throw new ProponoException("ERROR: authorization returned code: " + method.getStatusCode()); } break; case AUTHORIZED: if (token != null && secret != null) { accessToken = token; tokenSecret = secret; state = State.ACCESS_TOKEN; } else { throw new ProponoException("ERROR: accessToken or tokenSecret is null"); } break; } }
From source file:com.cyberway.issue.crawler.fetcher.FetchHTTP.java
protected void innerProcess(final CrawlURI curi) throws InterruptedException { if (!canFetch(curi)) { // Cannot fetch this, due to protocol, retries, or other problems return;/* w ww . jav a 2 s . c o m*/ } this.curisHandled++; // Note begin time curi.putLong(A_FETCH_BEGAN_TIME, System.currentTimeMillis()); // Get a reference to the HttpRecorder that is set into this ToeThread. HttpRecorder rec = HttpRecorder.getHttpRecorder(); // Shall we get a digest on the content downloaded? boolean digestContent = ((Boolean) getUncheckedAttribute(curi, ATTR_DIGEST_CONTENT)).booleanValue(); String algorithm = null; if (digestContent) { algorithm = ((String) getUncheckedAttribute(curi, ATTR_DIGEST_ALGORITHM)); rec.getRecordedInput().setDigest(algorithm); } else { // clear rec.getRecordedInput().setDigest((MessageDigest) null); } // Below we do two inner classes that add check of midfetch // filters just as we're about to receive the response body. String curiString = curi.getUURI().toString(); HttpMethodBase method = null; if (curi.isPost()) { method = new HttpRecorderPostMethod(curiString, rec) { protected void readResponseBody(HttpState state, HttpConnection conn) throws IOException, HttpException { addResponseContent(this, curi); if (checkMidfetchAbort(curi, this.httpRecorderMethod, conn)) { doAbort(curi, this, MIDFETCH_ABORT_LOG); } else { super.readResponseBody(state, conn); } } }; } else { method = new HttpRecorderGetMethod(curiString, rec) { protected void readResponseBody(HttpState state, HttpConnection conn) throws IOException, HttpException { addResponseContent(this, curi); if (checkMidfetchAbort(curi, this.httpRecorderMethod, conn)) { doAbort(curi, this, MIDFETCH_ABORT_LOG); } else { super.readResponseBody(state, conn); } } }; } HostConfiguration customConfigOrNull = configureMethod(curi, method); // Set httpRecorder into curi. Subsequent code both here and later // in extractors expects to find the HttpRecorder in the CrawlURI. curi.setHttpRecorder(rec); // Populate credentials. Set config so auth. is not automatic. boolean addedCredentials = populateCredentials(curi, method); method.setDoAuthentication(addedCredentials); // set hardMax on bytes (if set by operator) long hardMax = getMaxLength(curi); // set overall timeout (if set by operator) long timeoutMs = 1000 * getTimeout(curi); // Get max fetch rate (bytes/ms). It comes in in KB/sec long maxRateKBps = getMaxFetchRate(curi); rec.getRecordedInput().setLimits(hardMax, timeoutMs, maxRateKBps); try { this.http.executeMethod(customConfigOrNull, method); } catch (RecorderTooMuchHeaderException ex) { // when too much header material, abort like other truncations doAbort(curi, method, HEADER_TRUNC); } catch (IOException e) { failedExecuteCleanup(method, curi, e); return; } catch (ArrayIndexOutOfBoundsException e) { // For weird windows-only ArrayIndex exceptions in native // code... see // http://forum.java.sun.com/thread.jsp?forum=11&thread=378356 // treating as if it were an IOException failedExecuteCleanup(method, curi, e); return; } // set softMax on bytes to get (if implied by content-length) long softMax = method.getResponseContentLength(); try { if (!method.isAborted()) { // Force read-to-end, so that any socket hangs occur here, // not in later modules. rec.getRecordedInput().readFullyOrUntil(softMax); } } catch (RecorderTimeoutException ex) { doAbort(curi, method, TIMER_TRUNC); } catch (RecorderLengthExceededException ex) { doAbort(curi, method, LENGTH_TRUNC); } catch (IOException e) { cleanup(curi, e, "readFully", S_CONNECT_LOST); return; } catch (ArrayIndexOutOfBoundsException e) { // For weird windows-only ArrayIndex exceptions from native code // see http://forum.java.sun.com/thread.jsp?forum=11&thread=378356 // treating as if it were an IOException cleanup(curi, e, "readFully", S_CONNECT_LOST); return; } finally { // ensure recording has stopped rec.closeRecorders(); if (!method.isAborted()) { method.releaseConnection(); } // Note completion time curi.putLong(A_FETCH_COMPLETED_TIME, System.currentTimeMillis()); // Set the response charset into the HttpRecord if available. setCharacterEncoding(rec, method); setSizes(curi, rec); } if (digestContent) { curi.setContentDigest(algorithm, rec.getRecordedInput().getDigestValue()); } if (logger.isLoggable(Level.INFO)) { logger.info((curi.isPost() ? "POST" : "GET") + " " + curi.getUURI().toString() + " " + method.getStatusCode() + " " + rec.getRecordedInput().getSize() + " " + curi.getContentType()); } if (curi.isSuccess() && addedCredentials) { // Promote the credentials from the CrawlURI to the CrawlServer // so they are available for all subsequent CrawlURIs on this // server. promoteCredentials(curi); if (logger.isLoggable(Level.FINE)) { // Print out the cookie. Might help with the debugging. Header setCookie = method.getResponseHeader("set-cookie"); if (setCookie != null) { logger.fine(setCookie.toString().trim()); } } } else if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { // 401 is not 'success'. handle401(method, curi); } if (rec.getRecordedInput().isOpen()) { logger.severe(curi.toString() + " RIS still open. Should have" + " been closed by method release: " + Thread.currentThread().getName()); try { rec.getRecordedInput().close(); } catch (IOException e) { logger.log(Level.SEVERE, "second-chance RIS close failed", e); } } }
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page./*from w ww . j ava 2s . c o m*/ */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }
From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java
/** * Collect the HTTP header information and set them in the message context * * @param method HttpMethodBase from which to get information * @param msgContext the MessageContext in which to place the information... OR NOT! * @throws AxisFault if problems occur/* ww w .jav a 2 s . c om*/ */ protected void obtainHTTPHeaderInformation(HttpMethodBase method, MessageContext msgContext) throws AxisFault { // Set RESPONSE properties onto the REQUEST message context. They will need to be copied off the request context onto // the response context elsewhere, for example in the OutInOperationClient. Map transportHeaders = new CommonsTransportHeaders(method.getResponseHeaders()); msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, transportHeaders); msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, new Integer(method.getStatusCode())); Header header = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (header != null) { HeaderElement[] headers = header.getElements(); MessageContext inMessageContext = msgContext.getOperationContext() .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); Object contentType = header.getValue(); Object charSetEnc = null; for (int i = 0; i < headers.length; i++) { NameValuePair charsetEnc = headers[i].getParameterByName(HTTPConstants.CHAR_SET_ENCODING); if (charsetEnc != null) { charSetEnc = charsetEnc.getValue(); } } if (inMessageContext != null) { inMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType); inMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } else { // Transport details will be stored in a HashMap so that anybody interested can // retrieve them HashMap transportInfoMap = new HashMap(); transportInfoMap.put(Constants.Configuration.CONTENT_TYPE, contentType); transportInfoMap.put(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); //the HashMap is stored in the outgoing message. msgContext.setProperty(Constants.Configuration.TRANSPORT_INFO_MAP, transportInfoMap); } } String sessionCookie = null; // Process old style headers first Header[] cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE); String customCoookiId = (String) msgContext.getProperty(Constants.CUSTOM_COOKIE_ID); // process all the cookieHeaders, when load balancer is fronted it may require some cookies to function. sessionCookie = processCookieHeaders(cookieHeaders); // Overwrite old style cookies with new style ones if present cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE2); for (int i = 0; i < cookieHeaders.length; i++) { HeaderElement[] elements = cookieHeaders[i].getElements(); for (int e = 0; e < elements.length; e++) { HeaderElement element = elements[e]; if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) || Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } if (customCoookiId != null && customCoookiId.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } } } if (sessionCookie != null && !sessionCookie.isEmpty()) { msgContext.getServiceContext().setProperty(HTTPConstants.COOKIE_STRING, sessionCookie); } }
From source file:org.apache.axis2.transport.http.HTTPSender.java
/** * Used to handle the HTTP Response/* w w w.j a v a 2 s. c o m*/ * * @param msgContext - The MessageContext of the message * @param method - The HTTP method used * @throws IOException - Thrown in case an exception occurs */ private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException { int statusCode = method.getStatusCode(); HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode); log.trace("Handling response - " + statusCode); Set<Integer> nonErrorCodes = (Set<Integer>) msgContext .getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES); Set<Integer> errorCodes = new HashSet<Integer>(); String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); // Fixing // ESBJAVA-3178 if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) { for (String strRetryErrorCode : strRetryErrorCodes.split(",")) { try { errorCodes.add(Integer.valueOf(strRetryErrorCode)); } catch (NumberFormatException e) { log.warn(strRetryErrorCode + " is not a valid status code"); } } } if (statusCode == HttpStatus.SC_ACCEPTED) { /* When an HTTP 202 Accepted code has been received, this will be the case of an execution * of an in-only operation. In such a scenario, the HTTP response headers should be returned, * i.e. session cookies. */ obtainHTTPHeaderInformation(method, msgContext); // Since we don't expect any content with a 202 response, we must release the connection method.releaseConnection(); } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) { // Save the HttpMethod so that we can release the connection when cleaning up msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); processResponse(method, msgContext); } else if (!errorCodes.contains(statusCode) && (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR || statusCode == HttpStatus.SC_BAD_REQUEST || statusCode == HttpStatus.SC_CONFLICT)) { // Save the HttpMethod so that we can release the connection when cleaning up msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); String value = null; if (contenttypeHeader != null) { value = contenttypeHeader.getValue(); } OperationContext opContext = msgContext.getOperationContext(); if (opContext != null) { MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMessageContext != null) { inMessageContext.setProcessingFault(true); } } if (value != null) { processResponse(method, msgContext); } if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) { throw new AxisFault( Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText())); } } else if (nonErrorCodes != null && nonErrorCodes.contains(statusCode)) { msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); processResponse(method, msgContext); return; } else { // Since we don't process the response, we must release the connection immediately method.releaseConnection(); throw new AxisFault( Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText())); } }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
/** * Used to handle the HTTP Response//ww w .j a va2s . c o m * * @param msgContext * - The MessageContext of the message * @param method * - The HTTP method used * @throws IOException * - Thrown in case an exception occurs */ protected void handleResponse(MessageContext msgContext, Object httpMethodBase) throws IOException { HttpMethodBase method; if (httpMethodBase instanceof HttpMethodBase) { method = (HttpMethodBase) httpMethodBase; } else { log.trace("HttpMethodBase expected, but found - " + httpMethodBase); return; } int statusCode = method.getStatusCode(); HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode); log.trace("Handling response - " + statusCode); if (statusCode == HttpStatus.SC_ACCEPTED) { /* When an HTTP 202 Accepted code has been received, this will be the case of an execution * of an in-only operation. In such a scenario, the HTTP response headers should be returned, * i.e. session cookies. */ obtainHTTPHeaderInformation(method, msgContext); // Since we don't expect any content with a 202 response, we must release the connection method.releaseConnection(); } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) { // Save the HttpMethod so that we can release the connection when cleaning up msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); processResponse(method, msgContext); } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR || statusCode == HttpStatus.SC_BAD_REQUEST) { // Save the HttpMethod so that we can release the connection when // cleaning up msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); String value = null; if (contenttypeHeader != null) { value = contenttypeHeader.getValue(); } OperationContext opContext = msgContext.getOperationContext(); if (opContext != null) { MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMessageContext != null) { inMessageContext.setProcessingFault(true); } } if (value != null) { processResponse(method, msgContext); } if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) { throw new AxisFault( Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText())); } } else { // Since we don't process the response, we must release the // connection immediately method.releaseConnection(); throw new AxisFault( Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText())); } }
From source file:org.apache.ivy.util.url.HttpClientHandler.java
private boolean checkStatusCode(URL url, HttpMethodBase method) throws IOException { int status = method.getStatusCode(); if (status == HttpStatus.SC_OK) { return true; }/*from www. ja v a 2s .c o m*/ // IVY-1328: some servers return a 204 on a HEAD request if ("HEAD".equals(method.getName()) && (status == 204)) { return true; } Message.debug("HTTP response status: " + status + " url=" + url); if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { Message.warn("Your proxy requires authentication."); } else if (String.valueOf(status).startsWith("4")) { Message.verbose("CLIENT ERROR: " + method.getStatusText() + " url=" + url); } else if (String.valueOf(status).startsWith("5")) { Message.error("SERVER ERROR: " + method.getStatusText() + " url=" + url); } return false; }
From source file:org.apache.jetspeed.portlets.sso.SSOTicketPortlet.java
private String requestTicket(String url, RenderRequest request, RenderResponse response) { // ...set up URL and HttpClient stuff String ticket = ""; HttpClient client = new HttpClient(); HttpMethodBase httpMethod = null; httpMethod = new PostMethod(); //String useragentProperty = request.getProperty("User-Agent"); httpMethod.addRequestHeader("User-Agent", "Firefox"); httpMethod.setPath(url);/*from ww w .j av a 2s.com*/ try { client.executeMethod(httpMethod); int responseCode = httpMethod.getStatusCode(); if (responseCode >= 300 && responseCode <= 399) { // redirection that could not be handled automatically!!! (probably from a POST) Header locationHeader = httpMethod.getResponseHeader("location"); String redirectLocation = locationHeader != null ? locationHeader.getValue() : null; if (redirectLocation != null) { // one more time (assume most params are already encoded & new URL is using GET protocol!) return requestTicket(redirectLocation, null, null); } else { // The response is a redirect, but did not provide the new location for the resource. throw new PortletException( "Redirection code: " + responseCode + ", but with no redirectionLocation set."); } } else if (responseCode == 200) { // String body = httpMethod.getResponseBodyAsString(); // Header [] head = httpMethod.getResponseHeaders(); TicketParamRewriter ticketWriter = new TicketParamRewriter(); String ticketName = (String) request.getPreferences().getValue(SSO_PREF_TICKET_NAME, null); if (ticketName != null) { ticketWriter.setTicketName(ticketName); Reader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream()); createParserAdaptor().parse(ticketWriter, reader); ticket = ticketWriter.getTicket(); } } } catch (Exception e) { logger.error("Unexpected error during request ticket.", e); } return ticket; }