List of usage examples for org.apache.commons.httpclient HttpMethod getStatusLine
public abstract StatusLine getStatusLine();
From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(403, "User is not logged in"); return;//from ww w . jav a 2s .co m } if (!servletRequest.isUserInRole("HOPS_ADMIN")) { servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(), "You don't have the access right for this service"); return; } if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); } if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request // note: we won't transfer the protocol version because I'm not // sure it would truly be compatible String proxyRequestUri = rewriteUrlFromRequest(servletRequest); try { // Execute the request HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getLocalHost(); config.setLocalAddress(localAddress); String method = servletRequest.getMethod(); HttpMethod m; if (method.equalsIgnoreCase("PUT")) { m = new PutMethod(proxyRequestUri); RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(), servletRequest.getContentType()); ((PutMethod) m).setRequestEntity(requestEntity); } else { m = new GetMethod(proxyRequestUri); } Enumeration<String> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String headerName = names.nextElement(); String value = servletRequest.getHeader(headerName); if (PASS_THROUGH_HEADERS.contains(headerName)) { //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 (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { continue; } else { m.setRequestHeader(headerName, value); } } } String user = servletRequest.getRemoteUser(); if (user != null && !user.isEmpty()) { m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(config, m); // Process the response int statusCode = m.getStatusCode(); // Pass the response code. This method with the "reason phrase" is //deprecated but it's the only way to pass the reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase()); copyResponseHeaders(m, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(m, servletResponse); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java
private void submitHttpRequest(String address, MessageObject mo) throws Exception { HttpMethod httpMethod = null; try {//from www. j a v a 2 s. c o m httpMethod = buildHttpRequest(replacer.replaceValues(address, mo), mo); // authentication if (connector.isDispatcherUseAuthentication()) { List<String> authenticationPreferences = new ArrayList<String>(); if ("Digest".equalsIgnoreCase(connector.getDispatcherAuthenticationType())) { authenticationPreferences.add(AuthPolicy.DIGEST); logger.debug("using Digest authentication"); } else { authenticationPreferences.add(AuthPolicy.BASIC); logger.debug("using Basic authentication"); } client.getParams().setAuthenticationPreemptive(true); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authenticationPreferences); Credentials credentials = new UsernamePasswordCredentials( replacer.replaceValues(connector.getDispatcherUsername(), mo), replacer.replaceValues(connector.getDispatcherPassword(), mo)); client.getState().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials); logger.debug("using authentication with credentials: " + credentials); } client.getParams().setSoTimeout( NumberUtils.toInt(replacer.replaceValues(connector.getDispatcherSocketTimeout()), 30000)); // execute the method logger.debug( "executing method: type=" + httpMethod.getName() + ", uri=" + httpMethod.getURI().toString()); int statusCode = client.executeMethod(httpMethod); logger.debug("received status code: " + statusCode); String response = null; if (connector.isDispatcherIncludeHeadersInResponse()) { HttpMessageConverter converter = new HttpMessageConverter(); response = converter.httpResponseToXml(httpMethod.getStatusLine().toString(), httpMethod.getResponseHeaders(), httpMethod.getResponseBodyAsString()); } else { response = httpMethod.getResponseBodyAsString(); } if (statusCode < HttpStatus.SC_BAD_REQUEST) { messageObjectController.setSuccess(mo, response, null); // send to reply channel if ((connector.getDispatcherReplyChannelId() != null) && !connector.getDispatcherReplyChannelId().equals("sink")) { new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true); } } else { alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_404, "Received error response from HTTP server.", null); messageObjectController.setError(mo, Constants.ERROR_404, response, null, null); } } catch (Exception e) { throw e; } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:de.fuberlin.wiwiss.marbles.loading.CacheController.java
/** * Adds retrieved URL data to the cache// ww w .ja v a2 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.zenkey.net.prowser.Tab.java
/************************************************************************** * Writes tracing information that traces the request/response activity. * //from w ww. jav a 2 s. c o m * @param traceLevel * Indicates how much trace info to produce. * @param traceStream * An output stream where trace statements will be written. * @param httpMethod * The HttpMethod object of the request. */ private static void writeTrace(int traceLevel, PrintStream traceStream, HttpMethod httpMethod) { try { if (traceLevel >= TRACE_URI) { // Show trace output of the request URI traceStream .println("-------------------------------------------------------------------------------"); traceStream.println(httpMethod.getURI() + "\n"); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP request line traceStream.println(httpMethod.getName() + " " + httpMethod.getPath() + (httpMethod.getQueryString() == null ? "" : "?" + httpMethod.getQueryString()) + " " + httpMethod.getParams().getVersion().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP request headers for (Header header : httpMethod.getRequestHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } // Show trace of request entity body if (httpMethod instanceof PostMethod) { NameValuePair[] parameters = ((PostMethod) httpMethod).getParameters(); if (parameters != null) { // StringBuffer parameterString = new StringBuffer(); // for (NameValuePair parameter : parameters) { // parameterString.append(parameter.getName() + "=" + parameter.getValue() + "&"); // } // parameterString.deleteCharAt(parameterString.length() - 1); String parameterString = new String( ((ByteArrayRequestEntity) ((PostMethod) httpMethod).getRequestEntity()) .getContent(), "UTF-8"); traceStream.println(" |"); traceStream.println(" +-- " + parameterString); } } traceStream.println(); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP status line traceStream.println(httpMethod.getStatusLine().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP response headers for (Header header : httpMethod.getResponseHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } traceStream.println(); } if (traceLevel >= TRACE_BODY) { // Show trace output of the HTTP response body traceStream.println(httpMethod.getResponseBodyAsString()); traceStream.println(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
private byte[] executeMethod(HttpMethod method, final Context context) throws IOException, URIException, MalformedURLException, EngineException { Header[] requestHeaders, responseHeaders = null; byte[] result = null; String contents = null;/* ww w. jav a2 s . co m*/ int statuscode = -1; if (!context.requestedObject.runningThread.bContinue) return null; Engine.logBeans .debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")"); try { requestHeaders = method.getRequestHeaders(); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString()); statuscode = doExecuteMethod(method, context); Engine.logBeans.debug("(HttpConnector) Status: " + method.getStatusLine().toString()); responseHeaders = method.getResponseHeaders(); context.setResponseHeaders(responseHeaders); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString()); if (statuscode != -1) { InputStream in = method.getResponseBodyAsStream(); if (in != null) { /** * Retrieve response charset if available in responseHeaders */ charset = null; boolean checkGZip = false; // add GZip support #320 for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) { Header head = responseHeaders[i]; if (HeaderName.ContentType.is(head)) { context.contentType = head.getValue(); HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length && charset == null; j++) { NameValuePair nvp = els[j].getParameterByName("charset"); if (nvp != null) charset = nvp.getValue(); } } else if (HeaderName.ContentEncoding.is(head)) { checkGZip = true; HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length; j++) if ("gzip".equals(els[j].getName())) { Engine.logBeans.debug("(HttpConnector) Decode GZip stream"); in = new GZIPInputStream(in); } } } if (context.contentType != null && context.contentType.startsWith("multipart/") && context.requestedObject instanceof AbstractHttpTransaction) { Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType"); try { AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in), context.contentType); ByteArrayOutputStream bos = new ByteArrayOutputStream(); mp.nextPart(bos); result = bos.toByteArray(); if (transaction.getAllowDownloadAttachment()) { Document doc = context.outputDocument; Element attInfo = null; File file = File.createTempFile("c8o_", ".part"); for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) { try { file.deleteOnExit(); if (attInfo == null) { Engine.logBeans.debug("(HttpConnector) Saving attachment(s)"); attInfo = doc.createElement("AttachmentInfo"); doc.getDocumentElement().appendChild(attInfo); } Element att = doc.createElement("attachment"); attInfo.appendChild(att); String cid = bp.getContentID(); if (cid != null) { cid = cid.replaceFirst("^<?(.*?)>?$", "$1"); att.setAttribute("cid", "cid:" + cid); } Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid + " in file: " + file.getAbsolutePath()); att.setAttribute("filepath", file.getAbsolutePath()); Enumeration<javax.mail.Header> headers = GenericUtils .cast(bp.getAllHeaders()); while (headers.hasMoreElements()) { javax.mail.Header header = headers.nextElement(); Element eHeader = doc.createElement("header"); att.appendChild(eHeader); eHeader.setAttribute("name", header.getName()); eHeader.setAttribute("value", header.getValue()); } } catch (Exception e1) { Engine.logBeans .error("(HttpConnector) Failed to retrieve the attachment in " + file.getAbsolutePath(), e1); } file = File.createTempFile("c8o_", ".part"); } file.delete(); in.close(); } } catch (Exception e) { Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e); } } else { result = IOUtils.toByteArray(in); in.close(); } } if (Engine.logBeans.isTraceEnabled()) { contents = new String((result != null) ? result : new byte[] {}); Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents); } String redirectUrl, newuri; GetMethod redirectMethod = null; // Handles REDIRECTION through Location header if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location != null) { newuri = location.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } // ignore any data after the ";" character int split = newuri.indexOf(';'); if (split != -1) { newuri = newuri.substring(0, split); } redirectUrl = getAbsoluteUrl(method, newuri); Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl); redirectMethod = new GetMethod(redirectUrl); // set headers for (int i = 0; i < requestHeaders.length; i++) redirectMethod.setRequestHeader(requestHeaders[i]); referer = redirectUrl.startsWith("http") ? redirectUrl : (hostConfiguration.getHostURL() + redirectUrl); result = executeMethod(redirectMethod, context); // recurse } else { Engine.logBeans.debug("(HttpConnector) Invalid redirect!"); } } else { /* * String lwContents = contents.toLowerCase(); int index, i, * j, k, z; // Handles REDIRECTION through META Refresh if * (((index = lwContents.indexOf("http-equiv='refresh'")) != * -1) || ((index = * lwContents.indexOf("http-equiv=\"refresh\"")) != -1)) { * if ((i = lwContents.indexOf("content=", index + 20)) != * -1) { char c = lwContents.charAt(i+8); if ((j = * lwContents.indexOf("url=", i)) != -1) { if ((k = * lwContents.indexOf(c, j + 1)) != -1) { newuri = * lwContents.substring(j+4, k); redirectUrl = * getAbsoluteUrl(method,newuri); * Engine.logBeans.debug("(HttpConnector) Redirecting to : " * + redirectUrl); redirectMethod = new * GetMethod(redirectUrl); * * // set headers for (z=0; z<requestHeaders.length; z++) * redirectMethod.setRequestHeader(requestHeaders[z]); * * referer = redirectUrl; result = * executeMethod(redirectMethod, context); // recurse } } } * } // Handles FRAMESET else if * (lwContents.indexOf("frameset") != -1) { * Engine.logBeans.debug * ("(HttpConnector) Analyzing frameset..."); * StringTokenizer st = new StringTokenizer(lwContents); * StringEx newcontents = new StringEx(lwContents); while * (st.hasMoreTokens()) { String token = st.nextToken(); * String uri; if (token.startsWith("src=")) { if * ((token.indexOf("\"") != -1) || (token.indexOf("'") != * -1)) { token = token.substring(5); uri = * token.substring(0,token.length()-1); newuri = * getAbsoluteUrl(method,uri); * Engine.logBeans.trace("(HttpConnector) Replaced uri ("+ * uri +") with newuri("+ newuri +")"); * * newcontents.replaceAll(token,newuri); } } } * Engine.logBeans * .trace("(HttpConnector) New response content:\n"+ * newcontents); result = newcontents.toString().getBytes(); * } */ } } //Added by julienda - #3433 - 04/03/2013 AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction; if (abstractHttpTransaction.getHttpInfo()) { Document doc = context.outputDocument; //Remove the node HTTPInfo if we have a redirect NodeList nodeList = XMLUtils.findElements(context.outputDocument.getDocumentElement(), abstractHttpTransaction.getHttpInfoTagName()); if (nodeList != null) { XMLUtils.removeNodeListContent(nodeList); } //Parent Element httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName()); //Add requested URL Element urlElement = doc.createElement("url"); urlElement.setTextContent(method.getURI().toString()); httpInfoElement.appendChild(urlElement); //Add status code Element httpStatusElement = doc.createElement("status"); httpStatusElement.setAttribute("code", Integer.toString(statuscode)); httpStatusElement.setAttribute("text", method.getStatusText()); httpInfoElement.appendChild(httpStatusElement); //We add headers informations List<Header> headers = Arrays.asList(requestHeaders); if (!headers.isEmpty()) { Element httpHeadersElement = doc.createElement("headers"); for (int i = 0; i < headers.size(); i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", headers.get(i).getName()); elt.setAttribute("value", headers.get(i).getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } // we add response header information if (responseHeaders.length != 0) { Element httpHeadersElement = doc.createElement("responseHeaders"); for (int i = 0; i < responseHeaders.length; i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", responseHeaders[i].getName()); elt.setAttribute("value", responseHeaders[i].getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } doc.getDocumentElement().appendChild(httpInfoElement); } } finally { method.releaseConnection(); } return result; }
From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java
public SaxonDocument getStats(String collectionId) throws UnsupportedEncodingException, IOException, SaxonApiException, Exception { HttpClient client = new HttpClient(); HttpMethod method; String fq = !collectionId.isEmpty() ? "fq=parentIdentifier%3D" + collectionId + "&" : ""; String urlStr = this.solrHost + "/select?q=*%3A*&" + fq + "wt=xml&stats=true&" + "stats.field=beginPosition&" + "stats.field=endPosition&" + "stats.field=orbitNumber&" + "stats.field=acquisitionStation&" + "facet.field=productType&" + "facet.field=platformShortName&" + "facet.field=platformSerialIdentifier&" + "facet.field=instrument&" + "facet.field=sensorType&" + "facet.field=compositeType&" + "facet.field=processingLevel&" + "facet.field=orbitType&" + "stats.field=resolution&" + "facet.field=spectralRange&" + "stats.field=wavelengths&" + "facet.field=useLimitation&" + "facet.field=hasSecurityConstraints&" + "facet.field=organisationName&" + "facet.field=dissemination&" + "facet.field=parentIdentifier&" + "facet.field=productionStatus&" + "facet.field=acquisitionType&" + "stats.field=orbitNumber&" + "facet.field=orbitDirection&" + "stats.field=track&" + "stats.field=frame&" + "facet.field=swathIdentifier&" + "stats.field=cloudCover&" + "stats.field=snowCover&" + "facet.field=productQualityDegradation&" + "facet.field=productQualityDegradationTag&" + "facet.field=processorName&" + "facet.field=processingCenter&" + "stats.field=processingDate&" + "facet.field=sensorMode&" + "facet.field=archivingCenter&" + "facet.field=processingMode&" + "facet.field=acquisitionStation&" + "facet.field=acquisitionSubType&" + "stats.field=startTimeFromAscendingNode&" + "stats.field=completionTimeFromAscendingNode&" + "stats.field=illuminationAzimuthAngle&" + "stats.field=illuminationZenithAngle&" + "stats.field=illuminationElevationAngle&" + "facet.field=polarisationMode&" + "facet.field=polarisationChannels&" + "facet.field=antennaLookDirection&" + "stats.field=minimumIncidenceAngle&" + "stats.field=maximumIncidenceAngle&" + "stats.field=dopplerFrequency&" + "stats.field=incidenceAngleVariation&" + "rows=0&indent=true&facet=on&facet.mincount=1"; Log.debug("The following search is goint to be executed:" + urlStr); // Create a method instance. method = new GetMethod(urlStr); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. int statusCode = client.executeMethod(method); SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString()); Log.debug(solrResponse.getXMLDocumentString()); if (statusCode != HttpStatus.SC_OK) { Log.error("Method failed: " + method.getStatusLine()); String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()", XPathConstants.STRING); Log.error(solrResponse.getXMLDocumentString()); throw new Exception(errorMessage); }//from w w w. ja v a 2 s . c om return solrResponse; }
From source file:com.zimbra.cs.zimlet.ProxyServlet.java
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException { ZimbraLog.clearContext();// w w w. j a v a 2 s.co m boolean isAdmin = isAdminRequest(req); AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true); if (authToken == null) { String zAuthToken = req.getParameter(QP_ZAUTHTOKEN); if (zAuthToken != null) { try { authToken = AuthProvider.getAuthToken(zAuthToken); if (authToken.isExpired()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired"); return; } if (!authToken.isRegistered()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid"); return; } if (isAdmin && !authToken.isAdmin()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied"); return; } } catch (AuthTokenException e) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken"); return; } } } if (authToken == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie"); return; } // get the posted body before the server read and parse them. byte[] body = copyPostedData(req); // sanity check String target = req.getParameter(TARGET_PARAM); if (target == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // check for permission URL url = new URL(target); if (!isAdmin && !checkPermissionOnTarget(url, authToken)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // determine whether to return the target inline or store it as an upload String uploadParam = req.getParameter(UPLOAD_PARAM); boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true")); HttpMethod method = null; try { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); String reqMethod = req.getMethod(); if (reqMethod.equalsIgnoreCase("GET")) { method = new GetMethod(target); } else if (reqMethod.equalsIgnoreCase("POST")) { PostMethod post = new PostMethod(target); if (body != null) post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = post; } else if (reqMethod.equalsIgnoreCase("PUT")) { PutMethod put = new PutMethod(target); if (body != null) put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = put; } else if (reqMethod.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(target); } else { ZimbraLog.zimlet.info("unsupported request method: " + reqMethod); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // handle basic auth String auth, user, pass; auth = req.getParameter(AUTH_PARAM); user = req.getParameter(USER_PARAM); pass = req.getParameter(PASS_PARAM); if (auth != null && user != null && pass != null) { if (!auth.equals(AUTH_BASIC)) { ZimbraLog.zimlet.info("unsupported auth type: " + auth); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); client.setState(state); method.setDoAuthentication(true); } Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String hdr = (String) headers.nextElement(); ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr)); if (canProxyHeader(hdr)) { ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr)); if (hdr.equalsIgnoreCase("x-host")) method.getParams().setVirtualHost(req.getHeader(hdr)); else method.addRequestHeader(hdr, req.getHeader(hdr)); } } try { if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) { method.setFollowRedirects(true); } HttpClientUtil.executeMethod(client, method); } catch (HttpException ex) { ZimbraLog.zimlet.info("exception while proxying " + target, ex); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode(); // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line Header ctHeader = method.getResponseHeader("Content-Type"); String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue(); InputStream targetResponseBody = method.getResponseBodyAsStream(); if (asUpload) { String filename = req.getParameter(FILENAME_PARAM); if (filename == null || filename.equals("")) filename = new ContentType(contentType).getParameter("name"); if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null) filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()) .getParameter("filename"); if (filename == null || filename.equals("")) filename = "unknown"; List<Upload> uploads = null; if (targetResponseBody != null) { try { Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId()); uploads = Arrays.asList(up); } catch (ServiceException e) { if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED)) status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE; else status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } resp.setStatus(status); FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null); } else { resp.setStatus(status); resp.setContentType(contentType); for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName())) resp.addHeader(h.getName(), h.getValue()); if (targetResponseBody != null) ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true); } } finally { if (method != null) method.releaseConnection(); } }
From source file:nl.nn.adapterframework.http.HttpSender.java
public String sendMessageWithTimeoutGuarded(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { ParameterValueList pvl = null;//w ww . ja v a2s . co m try { if (prc != null && paramList != null) { pvl = prc.getValues(paramList); } } catch (ParameterException e) { throw new SenderException( getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e); } URI uri; HttpMethod httpmethod; HostConfiguration hostconfiguration = new HostConfiguration(hostconfigurationBase); try { if (urlParameter != null) { String url = (String) pvl.getParameterValue(getUrlParam()).getValue(); uri = getURI(url); } else { uri = staticUri; } Map<String, String> headersParamsMap = new HashMap<String, String>(); if (headersParams != null) { StringTokenizer st = new StringTokenizer(headersParams, ","); while (st.hasMoreElements()) { headersParamsMap.put(st.nextToken(), null); } } if (!isParamsInUrl()) { httpmethod = getPostMethodWithParamsInBody(uri, message, pvl, headersParamsMap, prc); } else { httpmethod = getMethod(uri, message, pvl, headersParamsMap); if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType()) && !"REPORT".equals(getMethodType())) { httpmethod.setFollowRedirects(isFollowRedirects()); } } int port = getPort(uri); if (socketfactory != null && "https".equals(uri.getScheme())) { Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port); hostconfiguration.setHost(uri.getHost(), port, authhttps); } else { hostconfiguration.setHost(uri.getHost(), port, uri.getScheme()); } log.info(getLogPrefix() + "configured httpclient for host [" + hostconfiguration.getHostURL() + "]"); if (credentials != null) { httpState.setCredentials(null, uri.getHost(), credentials); } } catch (URIException e) { throw new SenderException(e); } String result = null; int statusCode = -1; int count = getMaxExecuteRetries(); String msg = null; while (count-- >= 0 && statusCode == -1) { try { if (log.isDebugEnabled()) log.debug(getLogPrefix() + "executing method"); statusCode = httpclient.executeMethod(hostconfiguration, httpmethod, httpState); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "executed method"); if (statusCode != HttpServletResponse.SC_OK) { StatusLine statusline = httpmethod.getStatusLine(); if (statusline != null) { log.warn(getLogPrefix() + "status [" + statusline.toString() + "]"); } else { log.warn(getLogPrefix() + "no statusline found"); } } else { if (log.isDebugEnabled()) log.debug(getLogPrefix() + "status [" + statusCode + "]"); } HttpServletResponse response = null; if (isStreamResultToServlet()) { response = (HttpServletResponse) prc.getSession().get("restListenerServletResponse"); } String fileName = null; if (StringUtils.isNotEmpty(getStreamResultToFileNameSessionKey())) { fileName = (String) prc.getSession().get(getStreamResultToFileNameSessionKey()); } result = extractResult(httpmethod, prc, response, fileName); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "retrieved result [" + result + "]"); } catch (HttpException e) { Throwable throwable = e.getCause(); String cause = null; if (throwable != null) { cause = throwable.toString(); } msg = e.getMessage(); log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]"); } catch (IOException e) { httpmethod.abort(); if (e instanceof SocketTimeoutException) { throw new TimeOutException(e); } throw new SenderException(e); } finally { // In case of storeResultAsStreamInSessionKey release connection // is done by ReleaseConnectionAfterReadInputStream. if (StringUtils.isEmpty(getStoreResultAsStreamInSessionKey())) { httpmethod.releaseConnection(); } } } if (statusCode == -1) { if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) { //java.net.SocketTimeoutException: Read timed out throw new TimeOutException("Failed to recover from timeout exception"); } throw new SenderException("Failed to recover from exception"); } if (isXhtml() && StringUtils.isNotEmpty(result)) { result = XmlUtils.skipDocTypeDeclaration(result.trim()); if (result.startsWith("<html>") || result.startsWith("<html ")) { CleanerProperties props = new CleanerProperties(); HtmlCleaner cleaner = new HtmlCleaner(props); TagNode tagNode = cleaner.clean(result); result = new SimpleXmlSerializer(props).getXmlAsString(tagNode); if (transformerPool != null) { log.debug(getLogPrefix() + " transforming result [" + result + "]"); ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true); try { result = transformerPool.transform(prc_xslt.getInputSource(), null); } catch (Exception e) { throw new SenderException("Exception on transforming input", e); } } } } return result; }
From source file:org.apache.camel.component.http.HttpProducer.java
protected Exception populateHttpOperationFailedException(Exchange exchange, HttpMethod method, int responseCode) throws IOException, ClassNotFoundException { Exception answer;/* w w w . jav a 2s . c om*/ String uri = method.getURI().toString(); String statusText = method.getStatusLine() != null ? method.getStatusLine().getReasonPhrase() : null; Map<String, String> headers = extractResponseHeaders(method.getResponseHeaders()); Object responseBody = extractResponseBody(method, exchange); if (transferException && responseBody != null && responseBody instanceof Exception) { // if the response was a serialized exception then use that return (Exception) responseBody; } // make a defensive copy of the response body in the exception so its detached from the cache String copy = null; if (responseBody != null) { copy = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, responseBody); } if (responseCode >= 300 && responseCode < 400) { String redirectLocation; Header locationHeader = method.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); answer = new HttpOperationFailedException(uri, responseCode, statusText, redirectLocation, headers, copy); } else { // no redirect location answer = new HttpOperationFailedException(uri, responseCode, statusText, null, headers, copy); } } else { // internal server error (error code 500) answer = new HttpOperationFailedException(uri, responseCode, statusText, null, headers, copy); } return answer; }
From source file:org.apache.cloudstack.network.element.SspClient.java
private String executeMethod(HttpMethod method) { String apiCallPath = null;//from w w w . j av a2s. co m try { apiCallPath = method.getName() + " " + method.getURI().toString(); } catch (URIException e) { s_logger.error("method getURI failed", e); } String response = null; try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { if (!login()) { return null; } try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } } s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine()); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod emethod = (EntityEnclosingMethod) method; RequestEntity reqEntity = emethod.getRequestEntity(); if (reqEntity instanceof StringRequestEntity) { StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity; s_logger.debug("ssp api request body:" + strReqEntity.getContent()); } else { s_logger.debug("ssp api request body:" + emethod.getRequestEntity()); } } s_logger.debug("ssp api response body:" + response); return response; }