List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeader
public abstract Header getResponseHeader(String paramString);
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers, Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts, Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId, PortletRequest portletRequest) throws IOException { byte[] bytes = null; HttpMethod httpMethod = null; HttpState httpState = null;// w w w. jav a 2s . c om try { _cookies.set(null); if (location == null) { return null; } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) { location = Http.HTTP_WITH_SLASH + location; } HostConfiguration hostConfiguration = getHostConfiguration(location); HttpClient httpClient = getClient(hostConfiguration); if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) { if (method.equals(Http.Method.POST)) { httpMethod = new PostMethod(location); } else { httpMethod = new PutMethod(location); } if (body != null) { RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(), body.getCharset()); EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; entityEnclosingMethod.setRequestEntity(requestEntity); } else if (method.equals(Http.Method.POST)) { PostMethod postMethod = (PostMethod) httpMethod; if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) { HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8); } processPostMethod(postMethod, fileParts, parts); } } else if (method.equals(Http.Method.DELETE)) { httpMethod = new DeleteMethod(location); } else if (method.equals(Http.Method.HEAD)) { httpMethod = new HeadMethod(location); } else { httpMethod = new GetMethod(location); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } } if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null) || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) { } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8); } if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) { httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT); } httpState = new HttpState(); if (ArrayUtil.isNotEmpty(cookies)) { org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies); httpState.addCookies(commonsCookies); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } if (auth != null) { httpMethod.setDoAuthentication(true); httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword())); } proxifyState(httpState, hostConfiguration); int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState); response.setResponseCode(responseCode); Header locationHeader = httpMethod.getResponseHeader("location"); if ((locationHeader != null) && !locationHeader.equals(location)) { String redirect = locationHeader.getValue(); if (followRedirects) { return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts, response, followRedirects, progressId, portletRequest); } else { response.setRedirect(redirect); } } InputStream inputStream = httpMethod.getResponseBodyAsStream(); if (inputStream != null) { int contentLength = 0; Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH); if (contentLengthHeader != null) { contentLength = GetterUtil.getInteger(contentLengthHeader.getValue()); response.setContentLength(contentLength); } Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE); if (contentType != null) { response.setContentType(contentType.getValue()); } if (Validator.isNotNull(progressId) && (portletRequest != null)) { ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream, contentLength, progressId); UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream( contentLength); try { progressInputStream.readAll(unsyncByteArrayOutputStream); } finally { progressInputStream.clearProgress(); } bytes = unsyncByteArrayOutputStream.unsafeGetByteArray(); unsyncByteArrayOutputStream.close(); } else { bytes = FileUtil.getBytes(inputStream); } } for (Header header : httpMethod.getResponseHeaders()) { response.addHeader(header.getName(), header.getValue()); } return bytes; } finally { try { if (httpState != null) { _cookies.set(toServletCookies(httpState.getCookies())); } } catch (Exception e) { _log.error(e, e); } try { if (httpMethod != null) { httpMethod.releaseConnection(); } } catch (Exception e) { _log.error(e, e); } } }
From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * // ww w . j av a2s .com * @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 * @throws EngineException */ private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { try { Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling"); if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) { System.setProperty("javax.net.debug", "all"); Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode"); } else { System.setProperty("javax.net.debug", ""); Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode"); } String baseUrl; String projectName; String connectorName; String contextName; String extraPath; { String requestURI = httpServletRequest.getRequestURI(); Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI); Matcher m = reg_fields.matcher(requestURI); if (m.matches() && m.groupCount() >= 5) { baseUrl = m.group(1); projectName = m.group(2); connectorName = m.group(3); contextName = m.group(4); extraPath = m.group(5); } else { throw new MalformedURLException( "The request doesn't contains needed fields : projectName, connectorName and contextName"); } } String sessionID = httpServletRequest.getSession().getId(); Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : " + extraPath + " ; sessionID : " + sessionID); Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName, connectorName, null); Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName); context.projectName = projectName; context.project = project; ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName); context.connector = proxyHttpConnector; context.connectorName = proxyHttpConnector.getName(); HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration; // Proxy configuration String proxyServer = Engine.theApp.proxyManager.getProxyServer(); String proxyUser = Engine.theApp.proxyManager.getProxyUser(); String proxyPassword = Engine.theApp.proxyManager.getProxyPassword(); int proxyPort = Engine.theApp.proxyManager.getProxyPort(); if (!proxyServer.equals("")) { hostConfiguration.setProxy(proxyServer, proxyPort); Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort); } else { // Remove old proxy configuration hostConfiguration.setProxyHost(null); } String targetHost = proxyHttpConnector.getServer(); Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost); int targetPort = proxyHttpConnector.getPort(); Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort); // Configuration SSL Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps()); CertificateManager certificateManager = proxyHttpConnector.certificateManager; boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates(); if (proxyHttpConnector.isHttps()) { Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties"); certificateManager.collectStoreInformation(context); Engine.logEngine.debug( "(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != targetPort)) { Engine.logEngine .debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, trustAllServerCertificates), targetPort); hostConfiguration.setHost(targetHost, targetPort, myhttps); } Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes"); } else { hostConfiguration.setHost(targetHost, targetPort); } HttpMethod httpMethodProxyRequest; String targetPath = proxyHttpConnector.getBaseDir() + extraPath; // Handle the query string if (httpServletRequest.getQueryString() != null) { targetPath += "?" + httpServletRequest.getQueryString(); } Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath); Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType); if (httpMethodType == HttpMethodType.GET) { // Create a GET request httpMethodProxyRequest = new GetMethod(); } else if (httpMethodType == HttpMethodType.POST) { // Create a standard POST request httpMethodProxyRequest = new PostMethod(); ((PostMethod) httpMethodProxyRequest) .setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream())); } else { throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType); } String charset = httpMethodProxyRequest.getParams().getUriCharset(); URI targetURI; try { targetURI = new URI(targetPath, true, charset); } catch (URIException e) { // Bugfix #1484 String newTargetPath = ""; for (String part : targetPath.split("&")) { if (!newTargetPath.equals("")) { newTargetPath += "&"; } String[] pair = part.split("="); try { newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "=" + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8") : ""); } catch (UnsupportedEncodingException ee) { newTargetPath = targetPath; } } targetURI = new URI(newTargetPath, true, charset); } httpMethodProxyRequest.setURI(targetURI); // Tells the method to automatically handle authentication. httpMethodProxyRequest.setDoAuthentication(true); HttpState httpState = getHttpState(proxyHttpConnector, context); String basicUser = proxyHttpConnector.getAuthUser(); String basicPassword = proxyHttpConnector.getAuthPassword(); String givenBasicUser = proxyHttpConnector.getGivenAuthUser(); String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword(); // Basic authentication configuration String realm = null; if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) { String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser); String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword); httpState.setCredentials(new AuthScope(targetHost, targetPort, realm), new UsernamePasswordCredentials(userName, userPassword)); Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******"); } // Setting basic authentication for proxy if (!proxyServer.equals("") && !proxyUser.equals("")) { httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword)); Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******"); } // Forward the request headers setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector); // Use the CEMS HttpClient HttpClient httpClient = Engine.theApp.httpClient; httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest, httpState); // 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 redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector); httpServletResponse.sendRedirect(redirect); Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")"); 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); Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)"); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:"); Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { String headerName = header.getName(); String headerValue = header.getValue(); if (!headerName.equalsIgnoreCase("Transfer-Encoding") && !headerName.equalsIgnoreCase("Set-Cookie")) { httpServletResponse.setHeader(headerName, headerValue); Engine.logEngine.debug(" " + headerName + "=" + headerValue); } } String contentType = null; Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type"); for (Header contentTypeHeader : contentTypeHeaders) { contentType = contentTypeHeader.getValue(); break; } String pageCharset = "UTF-8"; if (contentType != null) { int iCharset = contentType.indexOf("charset="); if (iCharset != -1) { pageCharset = contentType.substring(iCharset + "charset=".length()).trim(); } Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset); } InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream(); // Handle gzipped content Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding"); boolean bGZip = false, bDeflate = false; for (Header contentEncodingHeader : contentEncodingHeaders) { HeaderElement[] els = contentEncodingHeader.getElements(); for (int j = 0; j < els.length; j++) { if ("gzip".equals(els[j].getName())) { Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream"); siteIn = new GZIPInputStream(siteIn); bGZip = true; } else if ("deflate".equals(els[j].getName())) { Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream"); siteIn = new InflaterInputStream(siteIn, new Inflater(true)); bDeflate = true; } } } byte[] bytesDataResult; ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); // String resourceUrl = projectName + targetPath; String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST); try { // Read either from the cache, either from the remote server // InputStream is = proxyCacheManager.getResource(resourceUrl); // if (is != null) { // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache"); // siteIn = is; // } int c = siteIn.read(); while (c > -1) { baos.write(c); c = siteIn.read(); } // if (is != null) is.close(); } finally { context.statistics.stop(t, true); } bytesDataResult = baos.toByteArray(); baos.close(); Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!"); // if (isDynamicContent(httpServletRequest.getPathInfo(), // proxyHttpConnector.getDynamicContentFiles())) { Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content"); bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector, bytesDataResult); String billingClassName = context.getConnector().getBillingClassName(); if (billingClassName != null) { try { Engine.logContext.debug("Billing class name required: " + billingClassName); AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).newInstance(); Engine.logContext.debug("Executing the biller"); biller.insertBilling(context); } catch (Throwable e) { Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage()); } } // } // else { // Engine.logEngine.debug("(ReverseProxyServlet) Static content: " + // contentType); // // // Determine if the resource has already been cached or not // CacheEntry cacheEntry = // proxyCacheManager.getCacheEntry(resourceUrl); // if (cacheEntry instanceof FileCacheEntry) { // FileCacheEntry fileCacheEntry = (FileCacheEntry) cacheEntry; // File file = new File(fileCacheEntry.fileName); // if (!file.exists()) // proxyCacheManager.removeCacheEntry(cacheEntry); // cacheEntry = null; // } // if (cacheEntry == null) { // bytesDataResult = handleStringReplacements(contentType, // proxyHttpConnector, bytesDataResult); // // if (intProxyResponseCode == 200) { // Engine.logEngine.debug("(ReverseProxyServlet) Resource stored: " // + resourceUrl); // cacheEntry = proxyCacheManager.storeResponse(resourceUrl, // bytesDataResult); // cacheEntry.contentLength = bytesDataResult.length; // cacheEntry.contentType = contentType; // Engine.logEngine.debug("(ReverseProxyServlet) Cache entry: " + // cacheEntry); // } // } // } // Send the content to the client if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) { Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset)); } if (bGZip || bDeflate) { baos = new ByteArrayOutputStream(); OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos) : new DeflaterOutputStream(baos, new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true)); compressedOutputStream.write(bytesDataResult); compressedOutputStream.close(); bytesDataResult = baos.toByteArray(); baos.close(); } httpServletResponse.setContentLength(bytesDataResult.length); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); outputStreamClientResponse.write(bytesDataResult); Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission"); } catch (Exception e) { Engine.logEngine.error("Error while trying to proxy page", e); throw new ServletException("Error while trying to proxy page", e); } }
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;/* w w w . java2 s. c om*/ 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:nl.b3p.viewer.image.ImageCollector.java
/** * Load the image with a http-get//from www. j a v a 2 s .c o m * @param url The url to the image * @param user username * @param pass password * @return The image * @throws IOException * @throws Exception */ protected BufferedImage loadImage(String url, String user, String pass) throws IOException, Exception { HttpMethod method = null; try { method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Error connecting to server. HTTP status code: " + statusCode); } String mime = method.getResponseHeader("Content-Type").getValue(); return ImageTool.readImage(method, mime); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:nl.nn.adapterframework.http.HttpSender.java
public String extractResult(HttpMethod httpmethod, ParameterResolutionContext prc, HttpServletResponse response, String fileName) throws SenderException, IOException { int statusCode = httpmethod.getStatusCode(); boolean ok = false; if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey())) { prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode)); ok = true;/* w ww.ja v a 2 s . c o m*/ } else { if (statusCode == HttpServletResponse.SC_OK) { ok = true; } else { if (isIgnoreRedirects()) { if (statusCode == HttpServletResponse.SC_MOVED_PERMANENTLY || statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) { ok = true; } } } } if (!ok) { throw new SenderException(getLogPrefix() + "httpstatus " + statusCode + ": " + httpmethod.getStatusText() + " body: " + getResponseBodyAsString(httpmethod)); } if (response == null) { if (fileName == null) { if (isBase64()) { return getResponseBodyAsBase64(httpmethod); } else if (StringUtils.isNotEmpty(getStoreResultAsStreamInSessionKey())) { prc.getSession().put(getStoreResultAsStreamInSessionKey(), new ReleaseConnectionAfterReadInputStream(httpmethod, httpmethod.getResponseBodyAsStream())); return ""; } else if (StringUtils.isNotEmpty(getStoreResultAsByteArrayInSessionKey())) { InputStream is = httpmethod.getResponseBodyAsStream(); prc.getSession().put(getStoreResultAsByteArrayInSessionKey(), IOUtils.toByteArray(is)); return ""; } else if (isMultipartResponse()) { return handleMultipartResponse(httpmethod.getResponseHeader("Content-Type").getValue(), httpmethod.getResponseBodyAsStream(), prc, httpmethod); } else { //return httpmethod.getResponseBodyAsString(); return getResponseBodyAsString(httpmethod); } } else { InputStream is = httpmethod.getResponseBodyAsStream(); File file = new File(fileName); Misc.streamToFile(is, file); return fileName; } } else { streamResponseBody(httpmethod, response); return ""; } }
From source file:nl.nn.adapterframework.http.HttpSender.java
public void streamResponseBody(HttpMethod httpmethod, HttpServletResponse response) throws IOException { streamResponseBody(httpmethod.getResponseBodyAsStream(), httpmethod.getResponseHeader("Content-Type").getValue(), httpmethod.getResponseHeader("Content-Disposition").getValue(), response, log, getLogPrefix()); }
From source file:org.alfresco.encryption.DefaultEncryptionUtils.java
/** * Get the MAC (Message Authentication Code) on the HTTP response * // ww w. j a v a 2 s .c o m * @param res HttpMethod * @return the MAC * @throws IOException */ protected byte[] getResponseMac(HttpMethod res) throws IOException { Header header = res.getResponseHeader(HEADER_MAC); if (header != null) { return Base64.decode(header.getValue()); } else { return null; } }
From source file:org.alfresco.encryption.DefaultEncryptionUtils.java
/** * Get the timestamp on the HTTP response * //w ww . ja va 2 s. c o m * @param method HttpMethod * @return timestamp (ms, in UNIX time) * @throws IOException */ protected Long getResponseTimestamp(HttpMethod method) throws IOException { Header header = method.getResponseHeader(HEADER_TIMESTAMP); if (header != null) { return Long.valueOf(header.getValue()); } else { return null; } }
From source file:org.alfresco.encryption.DefaultEncryptionUtils.java
/** * Decode cipher algorithm parameters from the HTTP method * /* ww w . j a va 2 s.co m*/ * @param method HttpMethod * @return decoded algorithm parameters * @throws IOException */ protected AlgorithmParameters decodeAlgorithmParameters(HttpMethod method) throws IOException { Header header = method.getResponseHeader(HEADER_ALGORITHM_PARAMETERS); if (header != null) { byte[] algorithmParams = Base64.decode(header.getValue()); AlgorithmParameters algorithmParameters = encryptor.decodeAlgorithmParameters(algorithmParams); return algorithmParameters; } else { return null; } }
From source file:org.alfresco.httpclient.AbstractHttpClient.java
/** * Send Request to the repository/*from www. j a va 2 s . c om*/ */ protected HttpMethod sendRemoteRequest(Request req) throws AuthenticationException, IOException { if (logger.isDebugEnabled()) { logger.debug(""); logger.debug("* Request: " + req.getMethod() + " " + req.getFullUri() + (req.getBody() == null ? "" : "\n" + new String(req.getBody(), "UTF-8"))); } HttpMethod method = createMethod(req); // execute method executeMethod(method); // Deal with redirect if (isRedirect(method)) { Header locationHeader = method.getResponseHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue(); method.setURI(new URI(redirectLocation, true)); httpClient.executeMethod(method); } } return method; }