List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeader
public abstract Header getResponseHeader(String paramString);
From source file:com.zimbra.cs.account.auth.HostedAuth.java
/** * zmprov md test.com zimbraAuthMech 'custom:hosted http://auth.customer.com:80' * /*from w ww . jav a 2 s. co m*/ * This custom auth module takes arguments in the following form: * {URL} [GET|POST - default is GET] [encryption method - defautl is plain] [auth protocol - default is imap] * e.g.: http://auth.customer.com:80 GET **/ public void authenticate(Account acct, String password, Map<String, Object> context, List<String> args) throws Exception { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpMethod method = null; String targetURL = args.get(0); /* if (args.size()>2) { authMethod = args.get(2); } if (args.size()>3) { authMethod = args.get(3); }*/ if (args.size() > 1) { if (args.get(1).equalsIgnoreCase("GET")) method = new GetMethod(targetURL); else method = new PostMethod(targetURL); } else method = new GetMethod(targetURL); if (context.get(AuthContext.AC_ORIGINATING_CLIENT_IP) != null) method.addRequestHeader(HEADER_CLIENT_IP, context.get(AuthContext.AC_ORIGINATING_CLIENT_IP).toString()); if (context.get(AuthContext.AC_REMOTE_IP) != null) method.addRequestHeader(HEADER_X_ZIMBRA_REMOTE_ADDR, context.get(AuthContext.AC_REMOTE_IP).toString()); method.addRequestHeader(HEADER_AUTH_USER, acct.getName()); method.addRequestHeader(HEADER_AUTH_PASSWORD, password); AuthContext.Protocol proto = (AuthContext.Protocol) context.get(AuthContext.AC_PROTOCOL); if (proto != null) method.addRequestHeader(HEADER_AUTH_PROTOCOL, proto.toString()); if (context.get(AuthContext.AC_USER_AGENT) != null) method.addRequestHeader(HEADER_AUTH_USER_AGENT, context.get(AuthContext.AC_USER_AGENT).toString()); try { HttpClientUtil.executeMethod(client, method); } catch (HttpException ex) { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), acct.getName(), "HTTP request to remote authentication server failed", ex); } catch (IOException ex) { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), acct.getName(), "HTTP request to remote authentication server failed", ex); } finally { if (method != null) method.releaseConnection(); } int status = method.getStatusCode(); if (status != HttpStatus.SC_OK) { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), "HTTP request to remote authentication server failed. Remote response code: " + Integer.toString(status)); } String responseMessage; if (method.getResponseHeader(HEADER_AUTH_STATUS) != null) { responseMessage = method.getResponseHeader(HEADER_AUTH_STATUS).getValue(); } else { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), "Empty response from remote authentication server."); } if (responseMessage.equalsIgnoreCase(AUTH_STATUS_OK)) { return; } else { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), responseMessage); } }
From source file:it.geosolutions.httpproxy.HTTPProxy.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse} * //from ww w . j a va 2 s .c om * @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 * @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, ProxyInfo proxyInfo) throws IOException, ServletException { if (user != null && password != null) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password); httpClient.getState().setCredentials(AuthScope.ANY, upc); } httpMethodProxyRequest.setFollowRedirects(false); InputStream inputStreamServerResponse = null; ByteArrayOutputStream baos = null; try { // ////////////////////////// // Execute the request // ////////////////////////// int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); onRemoteResponse(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(Utils.LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + Utils.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( Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.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(Utils.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(Utils.HTTP_HEADER_ACCEPT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING)) continue; // else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE)) // continue; else httpServletResponse.setHeader(header.getName(), header.getValue()); } // /////////////////////////////////// // Send the content to the client // /////////////////////////////////// inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream(); if (inputStreamServerResponse != null) { byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()]; baos = new ByteArrayOutputStream(b.length); int read = 0; while ((read = inputStreamServerResponse.read(b)) > 0) { baos.write(b, 0, read); baos.flush(); } baos.writeTo(httpServletResponse.getOutputStream()); } } catch (HttpException e) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e); } finally { try { if (inputStreamServerResponse != null) inputStreamServerResponse.close(); } catch (IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error closing request input stream ", e); throw new ServletException(e.getMessage()); } try { if (baos != null) { baos.flush(); baos.close(); } } catch (IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error closing response stream ", e); throw new ServletException(e.getMessage()); } httpMethodProxyRequest.releaseConnection(); } }
From source file:ch.ksfx.web.services.spidering.http.WebEngine.java
public void loadResource(Resource resource) { HttpMethod httpMethod; try {/*from w w w . jav a 2 s . c o m*/ if (/*resource.getHttpMethod().equals(GET)*/true) { String url = resource.getUrl(); if (url != null) { url = url.replaceAll("&", "&"); url = url.replaceAll(""", "\""); } httpMethod = this.httpClientHelper.executeGetMethod(url); } else { //TODO implement POST functionality /* NameValuePair[] nameValuePairs = new NameValuePair[resource.getPostData().size()]; for(int i = 0; i < resource.getPostData().size(); i++) { nameValuePairs[i] = new NameValuePair(resource.getPostData().get(i).getName(), resource.getPostData().get(i).getValue()); } String url = resource.getURL().toString(); if (url != null) { url = url.replaceAll("&","&"); url = url.replaceAll(""","\""); } httpMethod = this.httpClientHelper.executePostMethod(url, nameValuePairs); */ } } catch (Exception e) { resource.setLoadSucceed(false); resource.setHttpStatusCode(222); logger.log(Level.SEVERE, "Unable to load resource", e); return; } if (httpMethod == null) { resource.setLoadSucceed(false); return; } if (httpMethod.getStatusCode() != HttpStatus.SC_OK) { try { resource.setUrl(httpMethod.getURI().toString()); for (Header header : httpMethod.getResponseHeaders()) { resource.addResponseHeader(new ResponseHeader(header.getName(), header.getValue())); } resource.setHttpStatusCode(httpMethod.getStatusCode()); } catch (Exception e) { logger.warning(e.getMessage()); e.printStackTrace(); } return; } try { if (httpMethod.getResponseHeader("Content-Encoding") != null && httpMethod.getResponseHeader("Content-Encoding").getValue().contains("gzip")) { BufferedInputStream in = new BufferedInputStream( new GZIPInputStream(httpMethod.getResponseBodyAsStream())); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) >= 0) { out.write(buffer, 0, length); } resource.setRawContent(out.toByteArray()); resource.setSize(new Long(out.toByteArray().length)); } else { BufferedInputStream in = new BufferedInputStream(httpMethod.getResponseBodyAsStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) >= 0) { out.write(buffer, 0, length); } resource.setRawContent(out.toByteArray()); resource.setSize(new Long(out.toByteArray().length)); } resource.setHttpStatusCode(httpMethod.getStatusCode()); resource.setLoadSucceed(true); resource.setMimeType(recognizeMimeType(resource, httpMethod)); if (resource.getMimeType().startsWith("text") || resource.getMimeType().equals("application/json")) { resource.setContent(EncodingHelper.encode(resource.getRawContent(), resource.getEncoding(), ((HttpMethodBase) httpMethod).getResponseCharSet())); } else { resource.setIsBinary(true); } } catch (IOException e) { e.printStackTrace(); logger.log(Level.SEVERE, "Unable to load resource", e); } finally { httpMethod.releaseConnection(); } }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<AppLicense> getAppLicensesForCurrentUser() throws Exception { List<AppLicense> appLicenses = new ArrayList<AppLicense>(); String uri = String.format(_baseUri + "/LearningObjectService.svc/AppLicensesForCurrentUser"); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); try {/*from ww w . j a v a2 s . c o m*/ int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) { appLicenses = deserializeXMLToAppLicenses(method.getResponseBodyAsStream()); } } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return appLicenses; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public Site getSiteForCurrentUser() throws Exception { String uri = String.format(_baseUri + "/LearningObjectService.svc/SiteForCurrentUser"); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); Site siteForUser = null;/*from w w w .j a va2 s . co m*/ try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) { siteForUser = deserializeXMLToSite(method.getResponseBodyAsStream()); } else { return null; } } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return siteForUser; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
/** * Returns customer settings/* w w w . j ava 2 s. c o m*/ */ public CustomerSettings getCustomerSettings() throws Exception { String uri = String.format(_baseUri + "/LearningObjectService.svc/CustomerSettings"); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); CustomerSettings customerSettings = null; try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) { customerSettings = deserializeXMLToCustomerSettings(method.getResponseBodyAsStream()); } else { return null; } } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return customerSettings; }
From source file:io.hops.hopsworks.api.jobs.JobService.java
/** * Get the job ui for the specified job. * This act as a proxy to get the job ui from yarn * <p>/*from w ww.j a v a2 s . c om*/ * @param appId * @param param * @param sc * @param req * @return */ @GET @Path("/{appId}/prox/{path: .+}") @Produces(MediaType.WILDCARD) @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getProxy(@PathParam("appId") final String appId, @PathParam("path") final String param, @Context SecurityContext sc, @Context HttpServletRequest req) { Response response = checkAccessRight(appId); if (response != null) { return response; } try { String trackingUrl; if (param.matches("http([a-zA-Z,:,/,.,0-9,-])+:([0-9])+(.)+")) { trackingUrl = param; } else { trackingUrl = "http://" + param; } trackingUrl = trackingUrl.replace("@hwqm", "?"); if (!hasAppAccessRight(trackingUrl)) { LOGGER.log(Level.SEVERE, "A user is trying to access an app outside their project!"); return Response.status(Response.Status.FORBIDDEN).build(); } org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(trackingUrl, false); HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); final HttpMethod method = new GetMethod(uri.getEscapedURI()); Enumeration<String> names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String value = req.getHeader(name); if (PASS_THROUGH_HEADERS.contains(name)) { //yarn does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (!name.toLowerCase().equals("accept-encoding") || trackingUrl.contains(".js")) { method.setRequestHeader(name, value); } } } String user = req.getRemoteUser(); if (user != null && !user.isEmpty()) { method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(method); Response.ResponseBuilder responseBuilder = noCacheResponse .getNoCacheResponseBuilder(Response.Status.OK); for (Header header : method.getResponseHeaders()) { responseBuilder.header(header.getName(), header.getValue()); } //method.getPath().contains("/allexecutors") is needed to replace the links under Executors tab //which are in a json response object if (method.getResponseHeader("Content-Type") == null || method.getResponseHeader("Content-Type").getValue().contains("html") || method.getPath().contains("/allexecutors")) { final String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort(); if (method.getResponseHeader("Content-Length") == null) { responseBuilder.entity(new StreamingOutput() { @Override public void write(OutputStream out) throws IOException, WebApplicationException { Writer writer = new BufferedWriter(new OutputStreamWriter(out)); InputStream stream = method.getResponseBodyAsStream(); Reader in = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[4 * 1024]; String remaining = ""; int n; while ((n = in.read(buffer)) != -1) { StringBuilder strb = new StringBuilder(); strb.append(buffer, 0, n); String s = remaining + strb.toString(); remaining = s.substring(s.lastIndexOf(">") + 1, s.length()); s = hopify(s.substring(0, s.lastIndexOf(">") + 1), param, appId, source); writer.write(s); } writer.flush(); } }); } else { String s = hopify(method.getResponseBodyAsString(), param, appId, source); responseBuilder.entity(s); responseBuilder.header("Content-Length", s.length()); } } else { responseBuilder.entity(new StreamingOutput() { @Override public void write(OutputStream out) throws IOException, WebApplicationException { InputStream stream = method.getResponseBodyAsStream(); org.apache.hadoop.io.IOUtils.copyBytes(stream, out, 4096, true); out.flush(); } }); } return responseBuilder.build(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "exception while geting job ui " + e.getLocalizedMessage(), e); return noCacheResponse.getNoCacheResponseBuilder(Response.Status.NOT_FOUND).build(); } }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<Organisation> getOrganisationsForCurrentUser() throws Exception { String uri = String.format(_baseUri + "/LearningObjectService.svc/OrganizationsForCurrentUser"); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); List<Organisation> organizationsForUser = new ArrayList<Organisation>(); try {/*from www . j a va2 s .co m*/ int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) { organizationsForUser = deserializeXMLToOrganisations(method.getResponseBodyAsStream()); } else { return null; } } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return organizationsForUser; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<RubricCriteriaItem> getRubricCriteria(int learningObjectId, int instanceId) throws Exception { String uri = String.format( _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/RubricCriteria", learningObjectId, instanceId); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); List<RubricCriteriaItem> criteriaCreator = new ArrayList<RubricCriteriaItem>(); try {/*from w w w. j a va 2 s . c o m*/ int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) { criteriaCreator = deserializeXMLToCriteria(method.getResponseBodyAsStream()); } else { return null; } } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return criteriaCreator; }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public List<LearningObjective> getLearningObjectives(int learningObjectId, int instanceId) throws Exception { String uri = String.format( _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectives", learningObjectId, instanceId); HttpMethod method = getInitializedHttpMethod(_httpClient, uri, HttpMethodType.GET); List<LearningObjective> objectivesCreator = new ArrayList<LearningObjective>(); try {//from w w w .j a v a 2 s.com int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HTTPException(statusCode); } else { if (Integer.parseInt(method.getResponseHeader("Content-Length").getValue()) > 0) { objectivesCreator = deserializeXMLToListOfLearningObjectives(method.getResponseBodyAsStream()); } else { return null; } } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } return objectivesCreator; }