List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:org.nunux.poc.portal.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/*w ww.j a v a2 s .c om*/ * @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 */ 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("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { 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 if (header.getName().equals("Set-Cookie")) { String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } 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:org.nuxeo.jira.NuxeoServerInfoCollector.java
public static File collectNuxeoServerInfoAsZip(String serverURL, String userName, String password) throws HttpException, IOException { HttpClient httpClient = new HttpClient(); HttpMethod getMethod = null; try {//from w w w . ja v a 2s. c o m getMethod = new GetMethod(serverURL + "/site/collectServerInfo/info.zip"); executeGetMethod(httpClient, getMethod, userName, password); InputStream in = getMethod.getResponseBodyAsStream(); File tmpFile = File.createTempFile("NXserverInfo-", ".zip"); tmpFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tmpFile); byte[] bytes = new byte[1024]; try { int read; while ((read = in.read(bytes)) > 0) { out.write(bytes, 0, read); } } finally { in.close(); out.close(); } return tmpFile; } finally { getMethod.releaseConnection(); } }
From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java
/** * @param httpMethod//from w w w .j a v a2 s .com * @param responseCode * @return A HttpResponse object made by consuming the response of the given * HttpMethod. * @throws java.io.IOException */ private HttpResponse makeResponse(HttpMethod httpMethod, int responseCode) throws IOException { Map<String, String> headers = Maps.newHashMap(); if (httpMethod.getResponseHeaders() != null) { for (Header h : httpMethod.getResponseHeaders()) { headers.put(h.getName(), h.getValue()); } } // The first header is always null here to provide the response body. headers.remove(null); // Find the response stream - the error stream may be valid in cases // where the input stream is not. InputStream responseBodyStream = null; try { responseBodyStream = httpMethod.getResponseBodyAsStream(); } catch (IOException e) { // normal for 401, 403 and 404 responses, for example... } if (responseBodyStream == null) { // Fall back to zero length response. responseBodyStream = new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY); } String encoding = headers.get("Content-Encoding"); // Create the appropriate stream wrapper based on the encoding type. InputStream is = responseBodyStream; if (encoding == null) { is = responseBodyStream; } else if (encoding.equalsIgnoreCase("gzip")) { is = new GZIPInputStream(responseBodyStream); } else if (encoding.equalsIgnoreCase("deflate")) { Inflater inflater = new Inflater(true); is = new InflaterInputStream(responseBodyStream, inflater); } ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int totalBytesRead = 0; int currentBytesRead; while ((currentBytesRead = is.read(buffer)) != -1) { output.write(buffer, 0, currentBytesRead); totalBytesRead += currentBytesRead; if (maxObjSize > 0 && totalBytesRead > maxObjSize) { IOUtils.closeQuietly(is); IOUtils.closeQuietly(output); // Exceeded max # of bytes return HttpResponse.badrequest("Exceeded maximum number of bytes - " + this.maxObjSize); } } return new HttpResponseBuilder().setHttpStatusCode(responseCode).setResponse(output.toByteArray()) .addHeaders(headers).create(); }
From source file:org.obm.caldav.client.AbstractPushTest.java
private synchronized Document doRequest(HttpMethod hm) { Document xml = null;//w w w . j a va2s . c o m try { int ret = hc.executeMethod(hm); Header[] hs = hm.getResponseHeaders(); for (Header h : hs) { System.err.println("head[" + h.getName() + "] => " + h.getValue()); } if (ret == HttpStatus.SC_UNAUTHORIZED) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password); authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm); return null; } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) { InputStream is = hm.getResponseBodyAsStream(); if (is != null) { if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) { xml = DOMUtils.parse(is); DOMUtils.logDom(xml); } else { System.out.println(FileUtils.streamString(is, false)); } } } else { System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString()); } } catch (Exception e) { e.printStackTrace(); } finally { hm.releaseConnection(); } return xml; }
From source file:org.onebusaway.admin.service.server.impl.RssServiceAlertsSerivceImpl.java
protected List<ServiceAlertBean> pollServiceAdvisoryRssFeed() throws Exception { List<ServiceAlertBean> alerts = new ArrayList<ServiceAlertBean>(); if (_serviceAdvisoryUrlString == null) return alerts; HttpMethod httpget = new GetMethod(_serviceAdvisoryUrlString); int response = _httpClient.executeMethod(httpget); if (response != HttpStatus.SC_OK) { throw new Exception("service status poll failed, returned status code: " + response); }/*from w ww. j a v a2s . c o m*/ Document doc = _builder.build(httpget.getResponseBodyAsStream()); List<Element> elements = doc.getRootElement().getChild("channel").getChildren("item"); String language = doc.getRootElement().getChild("channel").getChildText("language"); if (language == null) language = _locale.getLanguage(); //they don't send language for this feed currently, perhaps they'll start? if (language.equals("en-us")) { // java prefers en language = _locale.getLanguage(); } for (Element itemElement : elements) { String title = itemElement.getChild("title").getValue(); String link = itemElement.getChild("link").getValue(); String description = itemElement.getChild("description").getValue(); String pubDateString = itemElement.getChild("pubDate").getValue(); String guid = itemElement.getChild("guid").getValue(); Date pubDate = _sdf.parse(pubDateString); List<SituationAffectsBean> affectedRouteIds = getRouteIds(title); ServiceAlertBean serviceAlertBean = new ServiceAlertBean(); serviceAlertBean.setSource(_alertSource); serviceAlertBean.setAllAffects(affectedRouteIds); serviceAlertBean.setSeverity(ESeverity.UNKNOWN); serviceAlertBean.setSummaries(Arrays.asList( new NaturalLanguageStringBean[] { new NaturalLanguageStringBean(description, language) })); serviceAlertBean.setReason(ServiceAlerts.ServiceAlert.Cause.UNKNOWN_CAUSE.name()); SituationConsequenceBean situationConsequenceBean = new SituationConsequenceBean(); situationConsequenceBean.setEffect(EEffect.SIGNIFICANT_DELAYS); serviceAlertBean .setConsequences(Arrays.asList(new SituationConsequenceBean[] { situationConsequenceBean })); serviceAlertBean.setCreationTime(pubDate.getTime()); serviceAlertBean.setDescriptions(Arrays.asList( new NaturalLanguageStringBean[] { new NaturalLanguageStringBean(description, language) })); serviceAlertBean.setId(new AgencyAndId(getAgencyId(), guid).toString()); serviceAlertBean.setUrls(Arrays .asList(new NaturalLanguageStringBean[] { new NaturalLanguageStringBean(link, language) })); alerts.add(serviceAlertBean); } return alerts; }
From source file:org.onebusaway.admin.service.server.impl.RssServiceAlertsSerivceImpl.java
protected List<ServiceAlertBean> pollServiceStatusRssFeed() throws Exception { List<ServiceAlertBean> alerts = new ArrayList<ServiceAlertBean>(); if (_serviceStatusUrlString == null) return alerts; HttpMethod httpget = new GetMethod(_serviceStatusUrlString); int response = _httpClient.executeMethod(httpget); if (response != HttpStatus.SC_OK) { throw new Exception("service status poll failed, returned status code: " + response); }/*w w w. j a v a2 s .c o m*/ Document doc = _builder.build(httpget.getResponseBodyAsStream()); List<Element> elements = doc.getRootElement().getChild("channel").getChildren("item"); String language = doc.getRootElement().getChild("channel").getChildText("language"); if (language == null) { language = _locale.getLanguage(); } if (language.equals("en-us")) { language = _locale.getLanguage(); } for (Element itemElement : elements) { String title = itemElement.getChild("title").getValue(); String link = itemElement.getChild("link").getValue(); String description = itemElement.getChild("description").getValue(); String pubDateString = itemElement.getChild("pubDate").getValue(); String guid = itemElement.getChild("guid").getValue(); Date pubDate = _sdf.parse(pubDateString); List<SituationAffectsBean> affectedRouteIds = getRouteIds(title); ServiceAlertBean serviceAlertBean = new ServiceAlertBean(); serviceAlertBean.setSource(_alertSource); serviceAlertBean.setAllAffects(affectedRouteIds); serviceAlertBean.setSeverity(ESeverity.UNKNOWN); serviceAlertBean.setSummaries(Arrays.asList( new NaturalLanguageStringBean[] { new NaturalLanguageStringBean(description, language) })); serviceAlertBean.setReason(ServiceAlerts.ServiceAlert.Cause.UNKNOWN_CAUSE.name()); SituationConsequenceBean situationConsequenceBean = new SituationConsequenceBean(); situationConsequenceBean.setEffect(EEffect.SIGNIFICANT_DELAYS); serviceAlertBean .setConsequences(Arrays.asList(new SituationConsequenceBean[] { situationConsequenceBean })); serviceAlertBean.setCreationTime(pubDate.getTime()); serviceAlertBean.setDescriptions(Arrays.asList( new NaturalLanguageStringBean[] { new NaturalLanguageStringBean(description, language) })); serviceAlertBean.setId(new AgencyAndId(getAgencyId(), guid).toString()); serviceAlertBean.setUrls(Arrays .asList(new NaturalLanguageStringBean[] { new NaturalLanguageStringBean(link, language) })); alerts.add(serviceAlertBean); } return alerts; }
From source file:org.onebusaway.enterprise.webapp.actions.status.service.StatusProviderImpl.java
@Override public StatusGroup getIcingaStatus() { StatusGroup group = new StatusGroup(); group.setTitle("System Monitoring"); group.setScope("Monitoring and Infrastructure notices"); group.setSource("Monitoring subsystem -- automated notifications"); IcingaResponse response = null;//from w w w. ja v a 2s .co m // fail if not configured! String baseUrl = _config.getConfigurationValueAsString("icinga.baseUrl", null); String command = _config.getConfigurationValueAsString("icinga.command", null); // be careful -- by default we aren't configured to do anything! if (baseUrl == null || command == null) { _log.info( "missing required configuration for status group: baseUrl=" + baseUrl + ", command=" + command); return group; } try { HttpClient client = new HttpClient(); String url = baseUrl + encode(command); HttpMethod method = new GetMethod(url); client.executeMethod(method); InputStream result = method.getResponseBodyAsStream(); ObjectMapper mapper = new ObjectMapper(); response = mapper.readValue(result, IcingaResponse.class); } catch (IOException e) { _log.error("Exception getting Icinga data " + e); group.addItem(exceptionStatus(e)); return group; } if (response == null) { group.addItem(exceptionStatus()); return group; } for (IcingaItem bean : response.getResult()) { StatusItem item = new StatusItem(); item.setDescription(bean.getServiceName()); item.setTitle(bean.getServiceDisplayName()); int state = bean.getServiceCurrentState(); StatusItem.Status status; if (state == 0) { status = StatusItem.Status.OK; } else if (state == 1) { status = StatusItem.Status.WARNING; } else { // 2 (or something even weirder!) status = StatusItem.Status.ERROR; } item.setStatus(status); group.addItem(item); } return group; }
From source file:org.onebusaway.enterprise.webapp.actions.status.service.StatusProviderImpl.java
@Override public StatusGroup getAgencyMetadataStatus() { StatusGroup group = new StatusGroup(); group.setTitle("General Notices"); group.setScope("Informational updates about holiday and schedule changes"); group.setSource("Agency Providers -- manual entry"); AgencyMetadata[] response = new AgencyMetadata[0]; String api = _config.getConfigurationValueAsString("status.obaApi", "http://localhost:8080/onebusaway-api-webapp/"); String endpoint = _config.getConfigurationValueAsString("status.obaApiAgencyMetadata", "api/where/agency-metadata/list.json"); String apikey = _config.getConfigurationValueAsString("display.obaApiKey", "OBAKEY"); String url = api + endpoint + "?key=" + apikey; try {/*from ww w . j a va2 s . c om*/ HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); client.executeMethod(method); InputStream result = method.getResponseBodyAsStream(); ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(result); JsonNode value = tree.findValue("data"); response = mapper.readValue(value, AgencyMetadata[].class); } catch (IOException e) { _log.error("Exception getting AgencyMetadata" + e); group.addItem(exceptionStatus(e)); return group; } if (response == null) { group.addItem(exceptionStatus()); return group; } for (AgencyMetadata bean : response) { if (!StringUtils.isEmpty(bean.getAgencyMessage())) { StatusItem item = new StatusItem(); item.setTitle(bean.getName() + ": " + bean.getAgencyMessage()); item.setStatus(StatusItem.Status.INFO); group.addItem(item); } } return group; }
From source file:org.onebusaway.nyc.integration_tests.nyc_webapp.VehicleTrackingWebappIntegrationTestIgnore.java
private String getResponseAsString(HttpMethod method) throws IOException { StringBuilder b = new StringBuilder(); String line = null;//from w ww.j a v a 2 s . com BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); while ((line = reader.readLine()) != null) b.append(line).append("\n"); reader.close(); return b.toString(); }
From source file:org.onebusaway.presentation.impl.ProxyServlet.java
private void executeMethod(HttpMethod method, HttpServletResponse resp) throws ServletException, IOException { HttpClient client = new HttpClient(); int status = client.executeMethod(method); resp.setStatus(status);/*w w w .j a va2 s . c om*/ // Pass response headers back to the client Header[] headerArrayResponse = method.getResponseHeaders(); for (Header header : headerArrayResponse) resp.setHeader(header.getName(), header.getValue()); // Send the content to the client InputStream in = method.getResponseBodyAsStream(); OutputStream out = resp.getOutputStream(); byte[] buffer = new byte[1024]; int rc; while ((rc = in.read(buffer)) != -1) out.write(buffer, 0, rc); }