List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeader
public abstract Header getResponseHeader(String paramString);
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails/*from ww w .java 2 s. 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 java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // 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 stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); 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); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } LOG.trace("Response has data? {}", !noData); if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }
From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java
/** * Fetch the response. If it is gzipped, unzip it. Checking encoding to * ensure data is read correctly//from ww w. j a va 2 s.c om * @param method * @return text response * @throws IOException */ private StringBuilder fetchResponse(HttpMethod method) throws IOException { Header contentTypeHdr = method.getResponseHeader("content-type"); String contentType = null; if (contentTypeHdr != null) contentType = contentTypeHdr.getValue(); String hdr = "charset="; int hdrLen = hdr.length(); String encoding = "ISO-8859-1"; if (contentType != null) { StringTokenizer t = new StringTokenizer(contentType, ";"); contentType = t.nextToken().trim(); while (t.hasMoreTokens()) { String param = t.nextToken().trim(); if (param.startsWith(hdr)) { encoding = param.substring(hdrLen); break; } } } Header contentEncodingHdr = method.getResponseHeader("content-encoding"); String contentEncoding = null; boolean isGzip = false; if (contentEncodingHdr != null) { contentEncoding = contentEncodingHdr.getValue(); if ("gzip".matches(contentEncoding.toLowerCase())) isGzip = true; else throw new IOException("cannot handle content-encoding " + contentEncoding); } if (contentType != null && (contentType.startsWith("text/") || texttypes.contains(contentType))) { InputStream is = method.getResponseBodyAsStream(); if (is != null) { Reader reader; if (isGzip) { reader = new InputStreamReader(new GZIPInputStream(is), encoding); } else { reader = new InputStreamReader(is, encoding); } // We have to close the input stream in order to return it to // the cache, so we get it for all content, even if we don't // use it. It's (I believe) a bug that the content handlers // used by getContent() don't close the input stream, but the // JDK team has marked those bugs as "will not fix." fetchResponseData(reader); reader.close(); } else { reInitBuffer(2048); // Ensure we have an empty buffer. } return charBuffer; } readResponse(method); return null; }
From source file:com.cyberway.issue.crawler.fetcher.FetchHTTP.java
/** * This method populates <code>curi</code> with response status and * content type./*from w w w . j a va 2 s. com*/ * @param curi CrawlURI to populate. * @param method Method to get response status and headers from. */ protected void addResponseContent(HttpMethod method, CrawlURI curi) { curi.setFetchStatus(method.getStatusCode()); Header ct = method.getResponseHeader("content-type"); curi.setContentType((ct == null) ? null : ct.getValue()); // Save method into curi too. Midfetch filters may want to leverage // info in here. curi.putObject(A_HTTP_TRANSACTION, method); }
From source file:it.geosdi.era.server.servlet.HTTPProxy.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @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 * @param digest //w w w . java 2 s. com * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String user, String password) throws IOException, ServletException { // Create a default HttpClient HttpClient httpClient = new HttpClient(); if (user != null && password != null) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password); httpClient.getState().setCredentials(AuthScope.ANY, upc); } httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // 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("Recieved 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 stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); 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); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { // Skip GZIP Responses if (header.getName().equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING)) continue; else httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream(); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int read; while ((read = inputStreamServerResponse.read()) > 0) { if (escapeHtmlFull(read) > 0) { outputStreamClientResponse.write(read); } } inputStreamServerResponse.close(); outputStreamClientResponse.write('\n'); outputStreamClientResponse.flush(); outputStreamClientResponse.close(); }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @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 java.io.IOException Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred *//*w w w . j a va 2 s. c o m*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // 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 stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); 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); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @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 *//*from w w w. j av a2 s .c om*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest) throws IOException, RedirectRequiredException { //Utils.traceRequest(httpServletRequest); // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); _log.debug("Sending request to " + httpMethodProxyRequest.getURI()); for (Header header : httpMethodProxyRequest.getRequestHeaders()) { _log.debug(" Header \"" + header.getName() + "\" = \"" + header.getValue() + "\""); } // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Persist the respose headers this.responseHeaderMap = new HashMap<String, List<String>>(); for (Header header : this.httpMethod.getResponseHeaders()) { responseHeaderMap.put(header.getName(), Arrays.asList(header.getValue())); } // 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(HttpConstants.STRING_LOCATION_HEADER) .getValue(); if (stringLocation == null) { throw new IOException("Recieved status code: " + stringStatusCode + " but no " + HttpConstants.STRING_LOCATION_HEADER + " header was found in the response"); } throw new RedirectRequiredException(new URL(stringLocation)); } 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(HttpConstants.STRING_CONTENT_LENGTH_HEADER_NAME, 0); //httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } // Pass the response code back to the client this.httpStatusCode = intProxyResponseCode; _log.debug("Response code was " + this.httpStatusCode); // Pass response headers back to the client // TODO: Implement support for proxying response headers //Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); //for(Header header : headerArrayResponse) { // httpServletResponse.setHeader(header.getName(), header.getValue()); //} // Send the content to the client //InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); //BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); //OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); //int intNextByte; //while ( ( intNextByte = bufferedInputStream.read() ) != -1 ) { // outputStreamClientResponse.write(intNextByte); //} }
From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * * @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 * @param httpServletRequest Request object pertaining to the proxied HTTP request * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred *//*from w ww .j a v a2s .c om*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a default HttpClient HttpClient httpClient = new HttpClient(); getCredential(httpServletRequest.getParameter("servername")); if (credentials != null) { httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getState().setCredentials(AuthScope.ANY, credentials); } httpMethodProxyRequest.setFollowRedirects(true); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); String response = httpMethodProxyRequest.getResponseBodyAsString(); // 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 stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } httpServletResponse.sendRedirect(stringLocation .replace(getProxyHostAndPort(httpServletRequest) + this.getProxyPath(), stringMyHostName)); 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); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, response); } else { response = new String(ungzip(httpMethodProxyRequest.getResponseBody())); } httpServletResponse.setContentLength(response.length()); } // Send the content to the client if (intProxyResponseCode == 200) httpServletResponse.getWriter().write(response); else httpServletResponse.getWriter().write(intProxyResponseCode); }
From source file:de.fuberlin.wiwiss.marbles.loading.CacheController.java
/** * Adds retrieved URL data to the cache//w ww . j a va 2 s. c o m * @param url The URL that was retrieved * @param data The retrieved data * @param method Used to obtain metadata */ public synchronized void addURLData(String url, Graph data, HttpMethod method) { RepositoryConnection dataConn = null; InferencerConnection inferencerConn = null; RepositoryConnection metaDataConn = null; try { dataConn = dataRepository.getConnection(); inferencerConn = (InferencerConnection) dataRepository.getSail().getConnection(); metaDataConn = metaDataRepository.getConnection(); URI urlDataContext = dataRepository.getValueFactory().createURI(url); URI urlInferencerContext = dataRepository.getValueFactory().createURI(url); URI urlMetadata = metaDataRepository.getValueFactory().createURI(url); /* Remove cached data and previous metadata */ inferencerConn.removeInferredStatement((Resource) null, null, null, urlInferencerContext); /* * Because inferencerConn now holds the transaction lock on the store, * we need to commit changes first or we'll run into a deadlock when removing statements * using dataConn. They could be removed using dataConn; but the problem * would remain for the adding of statements. */ inferencerConn.commit(); dataConn.remove((Resource) null, null, null, urlDataContext); metaDataConn.remove(urlMetadata, null, null, contextCacheDataURI); /* Add retrieved data */ if (data != null) dataConn.add(data); /* Add metadata */ if (method != null) { for (String headerField : cachedHeaderFields) { Header header; if (null != (header = method.getResponseHeader(headerField))) { metaDataConn.add(urlMetadata, metaDataRepository.getValueFactory().createURI(Constants.nsHTTP, headerField), metaDataRepository.getValueFactory().createLiteral(header.getValue()), contextCacheDataURI); } } /* Add status code */ if (null != method .getStatusLine()) /* or we'll run into a NullPointerException when calling getStatusCode() */ metaDataConn.add(urlMetadata, metaDataRepository.getValueFactory().createURI(Constants.nsHTTP, "responseCode"), metaDataRepository.getValueFactory().createLiteral(method.getStatusCode()), contextCacheDataURI); } /* We'll make use of the date header to specify when the document was retrieved */ metaDataConn.add(urlMetadata, metaDataRepository.getValueFactory().createURI(Constants.nsHTTP, "date"), metaDataRepository.getValueFactory().createLiteral(DateUtil.formatDate(new Date())), contextCacheDataURI); /* Commit */ // inferencerConn.commit(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } catch (SailException e) { e.printStackTrace(); } finally { if (dataConn != null) try { dataConn.close(); } catch (RepositoryException e) { e.printStackTrace(); } if (inferencerConn != null) try { inferencerConn.close(); } catch (SailException e) { e.printStackTrace(); } if (metaDataConn != null) try { metaDataConn.close(); } catch (RepositoryException e) { e.printStackTrace(); } } }
From source file:com.adobe.share.api.ShareAPI.java
/** * Parses the response from the Share service. * * @param method the method//w w w . jav a 2s .c o m * * @return the jSON object * * @throws HttpException the http exception * @throws IOException Signals that an I/O exception has occurred. * @throws ShareAPIException the share api exception */ protected final JSONObject parseResponse(final HttpMethod method) throws HttpException, IOException, ShareAPIException { JSONObject json = null; String content = null; if (LOGGER.isDebugEnabled()) { LOGGER.debug("URL: " + method.getURI().toString()); LOGGER.debug("Proxy: " + httpClient.getHostConfiguration().getProxyHost()); LOGGER.debug("Proxy Port: " + httpClient.getHostConfiguration().getProxyPort()); } try { int status = httpClient.executeMethod(method); final int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; OutputStream outputStream = new ByteArrayOutputStream(); InputStream inputStream = method.getResponseBodyAsStream(); while (true) { int read = inputStream.read(buffer); if (read == -1) { break; } outputStream.write(buffer, 0, read); } outputStream.close(); inputStream.close(); content = outputStream.toString(); if (method.getResponseHeader("Content-Type") != null) { String contentType = method.getResponseHeader("Content-Type").getValue(); if (method.getStatusCode() == STATUS_OK) { if (contentType.contains("application/xml")) { json = XML.toJSONObject(content); } } } if (status >= STATUS_BAD_REQUEST) { if (json != null) { throw new ShareAPIException(method.getStatusCode(), json.getJSONObject("response").getString("message")); } else { throw new ShareAPIException(method.getStatusCode(), content); } } } catch (JSONException e) { e.printStackTrace(); throw new ShareAPIException(method.getStatusCode(), content); } return json; }
From source file:freeciv.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @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 *//*from w w w .ja v a2 s . c om*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setFollowRedirects(false); String port = "" + httpServletRequest.getSession().getAttribute("civserverport"); String host = "" + httpServletRequest.getSession().getAttribute("civserverhost"); String username = "" + httpServletRequest.getSession().getAttribute("username"); httpMethodProxyRequest.addRequestHeader("civserverport", port); httpMethodProxyRequest.addRequestHeader("civserverhost", host); httpMethodProxyRequest.addRequestHeader("username", username); int intProxyResponseCode = 0; // Execute the request try { intProxyResponseCode = client.executeMethod(httpMethodProxyRequest); } catch (IOException ioErr) { //- If an I/O (transport) error occurs. Some transport exceptions can be recovered from. //- If a protocol exception occurs. Usually protocol exceptions cannot be recovered from. OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); httpServletResponse.setStatus(502); outputStreamClientResponse .write("Freeciv web client proxy not responding (most likely died).".getBytes()); httpMethodProxyRequest.releaseConnection(); return; } // 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) { httpMethodProxyRequest.releaseConnection(); throw new ServletException("Recieved 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 stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); httpMethodProxyRequest.releaseConnection(); 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); httpMethodProxyRequest.releaseConnection(); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } httpMethodProxyRequest.releaseConnection(); }