List of usage examples for org.apache.commons.httpclient HostConfiguration HostConfiguration
public HostConfiguration()
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
protected HostConfiguration getHostConfig(URI uri) throws Exception { Protocol protocol = Protocol.getProtocol(uri.getScheme().toLowerCase()); String host = uri.getHost();/*from ww w .j ava 2 s . co m*/ int port = uri.getPort(); HostConfiguration config = new HostConfiguration(); config.setHost(host, port, protocol); if (StringUtils.isNotBlank(httpConnector.getProxyHostname())) { // add proxy support config.setProxy(httpConnector.getProxyHostname(), httpConnector.getProxyPort()); } return config; }
From source file:org.mulgara.resolver.http.HttpContent.java
/** * Obtain the approrpriate connection method * // w w w .j a v a2 s . c om * @param methodType can be HEAD or GET * @return HttpMethodBase method */ private HttpMethod getConnectionMethod(int methodType) { if (methodType != GET && methodType != HEAD) { throw new IllegalArgumentException("Invalid method base supplied for connection"); } HostConfiguration config = new HostConfiguration(); config.setHost(host, port, Protocol.getProtocol(schema)); if (connection != null) { connection.releaseConnection(); connection.close(); connection = null; } try { connection = connectionManager.getConnectionWithTimeout(config, 0L); } catch (ConnectionPoolTimeoutException te) { // NOOP: SimpleHttpConnectionManager does not use timeouts } String proxyHost = System.getProperty("mulgara.httpcontent.proxyHost"); if (proxyHost != null && proxyHost.length() > 0) { connection.setProxyHost(proxyHost); } String proxyPort = System.getProperty("mulgara.httpcontent.proxyPort"); if (proxyPort != null && proxyPort.length() > 0) { connection.setProxyPort(Integer.parseInt(proxyPort)); } // default timeout to 30 seconds connection.getParams() .setConnectionTimeout(Integer.parseInt(System.getProperty("mulgara.httpcontent.timeout", "30000"))); String proxyUserName = System.getProperty("mulgara.httpcontent.proxyUserName"); if (proxyUserName != null) { state.setCredentials( new AuthScope(System.getProperty("mulgara.httpcontent.proxyRealmHost"), AuthScope.ANY_PORT, System.getProperty("mulgara.httpcontent.proxyRealm"), AuthScope.ANY_SCHEME), new UsernamePasswordCredentials(proxyUserName, System.getProperty("mulgara.httpcontent.proxyPassword"))); } HttpMethod method = null; if (methodType == HEAD) { method = new HeadMethod(httpUri.toString()); } else { method = new GetMethod(httpUri.toString()); } // manually follow redirects due to the // strictness of http client implementation method.setFollowRedirects(false); return method; }
From source file:org.n52.oxf.util.IOHelper.java
protected static HostConfiguration getHostConfiguration(URL serviceURL) { HostConfiguration hostConfig = new HostConfiguration(); // apply proxy settings: String host = System.getProperty("http.proxyHost"); String port = System.getProperty("http.proxyPort"); String nonProxyHosts = System.getProperty("http.nonProxyHosts"); // check if service url is among the non-proxy-hosts: boolean serviceIsNonProxyHost = false; if (nonProxyHosts != null && nonProxyHosts.length() > 0) { String[] nonProxyHostsArray = nonProxyHosts.split("\\|"); String serviceHost = serviceURL.getHost(); for (String nonProxyHost : nonProxyHostsArray) { if (nonProxyHost.equals(serviceHost)) { serviceIsNonProxyHost = true; break; }// www.ja v a2 s .c om } } // set proxy: if (serviceIsNonProxyHost == false && host != null && host.length() > 0 && port != null && port.length() > 0) { int portNumber = Integer.parseInt(port); hostConfig.setProxy(host, portNumber); LOGGER.info("Using proxy: " + host + " on port: " + portNumber); } return hostConfig; }
From source file:org.nuxeo.ecm.webdav.JackRabbitParallelBench.java
private HttpClient createClient() { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("localhost", PORT); //HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxConnectionsPerHost(hostConfig, 10); connectionManager.setParams(params); HttpClient client = new HttpClient(connectionManager); client.setHostConfiguration(hostConfig); Credentials creds = new UsernamePasswordCredentials(LOGIN, PASSWD); client.getState().setCredentials(AuthScope.ANY, creds); return client; }
From source file:org.nuxeo.ecm.webdav.JackrabbitWebdavClientTest.java
@BeforeClass public static void setUp() { // Setup code HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("localhost", PORT); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); int maxHostConnections = 20; params.setMaxConnectionsPerHost(hostConfig, maxHostConnections); connectionManager.setParams(params); client = new HttpClient(connectionManager); client.setHostConfiguration(hostConfig); Credentials creds = new UsernamePasswordCredentials("userId", "pw"); client.getState().setCredentials(AuthScope.ANY, creds); }
From source file:org.nuxeo.ecm.webdav.ParallelBench.java
private HttpClient createClient() { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("localhost", PORT); // HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxConnectionsPerHost(hostConfig, 10); connectionManager.setParams(params); HttpClient client = new HttpClient(connectionManager); client.setHostConfiguration(hostConfig); Credentials creds = new UsernamePasswordCredentials(LOGIN, PASSWD); client.getState().setCredentials(AuthScope.ANY, creds); return client; }
From source file:org.nuxeo.ecm.webdav.WebDavClientTest.java
protected static HttpClient createClient(String username, String password) { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("localhost", WebDavServerFeature.PORT); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); int maxHostConnections = 20; params.setMaxConnectionsPerHost(hostConfig, maxHostConnections); connectionManager.setParams(params); HttpClient httpClient = new HttpClient(connectionManager); httpClient.setHostConfiguration(hostConfig); Credentials creds = new UsernamePasswordCredentials(username, password); httpClient.getState().setCredentials(AuthScope.ANY, creds); httpClient.getParams().setAuthenticationPreemptive(true); return httpClient; }
From source file:org.openlaszlo.data.HTTPDataSource.java
/** * @param since last modified time to use * @param req//from w w w .jav a 2 s . com * @param url if null, ignored * @param redirCount number of redirs we've done */ public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl, int redirCount, int timeout) throws IOException, HttpException, DataSourceException, MalformedURLException { HttpMethodBase request = null; HostConfiguration hcfg = new HostConfiguration(); /* [todo hqm 2006-02-01] Anyone know why this code was here? It is setting the mime type to something which just confuses the DHTML parser. if (res != null) { res.setContentType("application/x-www-form-urlencoded;charset=UTF-8"); } */ try { // TODO: [2002-01-09 bloch] cope with cache-control // response headers (no-store, no-cache, must-revalidate, // proxy-revalidate). if (surl == null) { surl = getURL(req); } if (surl == null || surl.equals("")) { throw new MalformedURLException( /* (non-Javadoc) * @i18n.test * @org-mes="url is empty or null" */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-312")); } String reqType = ""; String headers = ""; if (req != null) { reqType = req.getParameter("reqtype"); headers = req.getParameter("headers"); } boolean isPost = false; mLogger.debug("reqtype = " + reqType); if (reqType != null && reqType.equals("POST")) { request = new LZPostMethod(); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); isPost = true; mLogger.debug("setting POST req method"); } else if (reqType != null && reqType.equals("PUT")) { request = new LZPutMethod(); // todo [hqm 2007] treat PUT like POST? isPost = true; mLogger.debug("setting PUT req method"); } else if (reqType != null && reqType.equals("DELETE")) { request = new LZDeleteMethod(); mLogger.debug("setting DELETE req method"); } else { mLogger.debug("setting GET (default) req method"); request = new LZGetMethod(); } request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0); // Proxy the request headers if (req != null) { LZHttpUtils.proxyRequestHeaders(req, request); } // Set headers from query string if (headers != null && headers.length() > 0) { StringTokenizer st = new StringTokenizer(headers, "\n"); while (st.hasMoreTokens()) { String h = st.nextToken(); int i = h.indexOf(":"); if (i > -1) { String n = h.substring(0, i); String v = h.substring(i + 2, h.length()); request.setRequestHeader(n, v); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="setting header " + p[0] + "=" + p[1] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-359", new Object[] { n, v })); } } } mLogger.debug("Parsing url"); URI uri = LZHttpUtils.newURI(surl); try { hcfg.setHost(uri); } catch (Exception e) { throw new MalformedURLException( /* (non-Javadoc) * @i18n.test * @org-mes="can't form uri from " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376", new Object[] { surl })); } // This gets us the url-encoded (escaped) path and query string String path = uri.getEscapedPath(); String query = uri.getEscapedQuery(); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="encoded path: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389", new Object[] { path })); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="encoded query: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397", new Object[] { query })); // This call takes a decoded (unescaped) path request.setPath(path); boolean hasQuery = (query != null && query.length() > 0); String rawcontent = null; // Newer rawpost protocol puts lzpostbody as a separate // top level query arg in the request. rawcontent = req.getParameter("lzpostbody"); if (isPost) { // Older rawpost protocol put the "lzpostbody" arg // embedded in the "url" args's query args if (rawcontent == null && hasQuery) { rawcontent = findQueryArg("lzpostbody", query); } if (rawcontent != null) { // Get the unescaped query string ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent)); } else if (hasQuery) { StringTokenizer st = new StringTokenizer(query, "&"); while (st.hasMoreTokens()) { String it = st.nextToken(); int i = it.indexOf("="); if (i > 0) { String n = it.substring(0, i); String v = it.substring(i + 1, it.length()); // POST encodes values during request ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8")); } else { mLogger.warn( /* (non-Javadoc) * @i18n.test * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-429", new Object[] { it })); } } } } else { // This call takes an encoded (escaped) query string request.setQueryString(query); } // Put in the If-Modified-Since headers if (since != -1) { String lms = LZHttpUtils.getDateString(since); request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="proxying lms: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450", new Object[] { lms })); } mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="setting up http client" */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460")); HttpClient htc = null; if (mConnectionMgr != null) { htc = new HttpClient(mConnectionMgr); } else { htc = new HttpClient(); } htc.setHostConfiguration(hcfg); // This is the data timeout mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="timeout set to " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478", new Object[] { timeout })); htc.getParams().setSoTimeout(timeout); // Set connection timeout the same htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout); // Set timeout for getting a connection htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout); // TODO: [2003-03-05 bloch] this should be more configurable (per app?) if (!isPost) { request.setFollowRedirects(mFollowRedirects > 0); } long t1 = System.currentTimeMillis(); mLogger.debug("starting remote request"); int rc = htc.executeMethod(hcfg, request); String status = HttpStatus.getStatusText(rc); if (status == null) { status = "" + rc; } mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="remote response status: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504", new Object[] { status })); HttpData data = null; if (isRedirect(rc) && mFollowRedirects > redirCount) { String loc = request.getResponseHeader("Location").toString(); String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length()); mLogger.info( /* (non-Javadoc) * @i18n.test * @org-mes="Following URL from redirect: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517", new Object[] { hostURI })); long t2 = System.currentTimeMillis(); if (timeout > 0) { timeout -= (t2 - t1); if (timeout < 0) { throw new InterruptedIOException( /* (non-Javadoc) * @i18n.test * @org-mes=p[0] + " timed out after redirecting to " + p[1] */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-529", new Object[] { surl, loc })); } } data = getDataOnce(req, res, since, hostURI, redirCount++, timeout); } else { data = new HttpData(request, rc); } if (req != null && res != null) { // proxy response headers LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure()); } return data; } catch (ConnectTimeoutException ce) { // Transduce to an InterrupedIOException, since lps takes these to be timeouts. if (request != null) { request.releaseConnection(); } throw new InterruptedIOException( /* (non-Javadoc) * @i18n.test * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs." */ org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557", new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout })); } catch (HttpRecoverableException hre) { if (request != null) { request.releaseConnection(); } throw hre; } catch (HttpException e) { if (request != null) { request.releaseConnection(); } throw e; } catch (IOException ie) { if (request != null) { request.releaseConnection(); } throw ie; } catch (RuntimeException e) { if (request != null) { request.releaseConnection(); } throw e; } }
From source file:org.openlaszlo.servlets.HistoryServlet.java
private void doSendHistory(HttpServletRequest req, HttpServletResponse res, Document doc) { mLogger.info("doSendHistory"); Element el = doc.getRootElement().getChild("root").getChild("history"); ServletOutputStream out = null;//from w w w .j a v a2s. com GetMethod request = null; String status = null; String body = null; try { out = res.getOutputStream(); request = new MyGetMethod(); String url = mURL + "?lzt=agentmessage" + "&url=" + URLEncoder.encode(mAgentURL) + "&group=" + mAgentGroup + "&to=*&range=user" + "&dset=" + mClientDataset + "&msg=" + URLEncoder.encode(getXMLHistory()); mLogger.debug("url: " + url); URI uri = new URI(url.toCharArray()); HostConfiguration hcfg = new HostConfiguration(); hcfg.setHost(uri); String path = uri.getEscapedPath(); String query = uri.getEscapedQuery(); mLogger.debug("path: " + path); mLogger.debug("query: " + query); request.setPath(path); request.setQueryString(query); HttpClient htc = new HttpClient(mConnectionMgr); htc.setHostConfiguration(hcfg); int rc = htc.executeMethod(hcfg, request); status = HttpStatus.getStatusText(rc); if (status == null) { status = "" + rc; } mLogger.debug("remote response status: " + status); body = request.getResponseBodyAsString(); mLogger.debug("response body: " + body); } catch (HttpRecoverableException e) { mLogger.debug("HttpRecoverableException: " + e.getMessage()); sendError(out, "<status message=\"HttpRecoverableException " + e.getMessage() + "\" />"); } catch (HttpException e) { mLogger.debug("HttpException: " + e.getMessage()); sendError(out, "<status message=\"HttpException " + e.getMessage() + "\" />"); } catch (IOException e) { mLogger.debug("IOException: " + e.getMessage()); sendError(out, "<status message=\"IOException " + e.getMessage() + "\" />"); } finally { if (request != null) { request.releaseConnection(); } } try { if (status != null && status.equals("OK")) { out.println("<status message=\"ok\">" + (body != null ? body : "") + "</status>"); } else { out.println("<status message=\"" + mURL + "?lzt=agentmessage" + " " + status + "\" />"); } out.flush(); } catch (IOException e) { mLogger.debug("Client IOException"); // ignore client ioexception } finally { close(out); } }
From source file:org.openlaszlo.servlets.responders.ResponderCompile.java
/** * @return File name for temporary LZX file that is the * result of this http pre-processing; null for a bad request * @param req request//w w w . j av a2s. c o m * @param fileName file name associated with request */ private String doPreProcessing(HttpServletRequest req, String fileName) throws IOException { // Do an http request for this and see what we get back. // StringBuffer s = req.getRequestURL(); int len = s.length(); // Remove the .lzx from the end of the URL if (len <= 4) { return null; } s.delete(len - 4, len); // FIXME [2002-12-15 bloch] does any/all of this need to be synchronized on session? // First get the temporary file name for this session HttpSession session = req.getSession(); String sid = session.getId(); String tempFileName = getTempFileName(fileName, sid); File tempFile = new File(tempFileName); tempFile.deleteOnExit(); // Now pre-process the request and copy the data to // the temporary file that is unique to this session // FIXME: query string processing String surl = s.toString(); URL url = new URL(surl); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="Preprocessing request at " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(), "051018-263", new Object[] { surl })); GetMethod getRequest = new LZGetMethod(); getRequest.setPath(url.getPath()); //getRequest.setQueryString(url.getQuery()); getRequest.setQueryString(req.getQueryString()); // Copy headers to request LZHttpUtils.proxyRequestHeaders(req, getRequest); // Mention the last modified time, if the file exists if (tempFile.exists()) { long lastModified = tempFile.lastModified(); getRequest.addRequestHeader("If-Modified-Since", LZHttpUtils.getDateString(lastModified)); } else { // Otherwise, create a listener that will clean up the tempfile // Note: web server administrators must make sure that their servers are killed // gracefully or temporary files will not be handled by the LZBindingListener. // Add a binding listener for this session that // will remove our temporary files LZBindingListener listener = (LZBindingListener) session.getAttribute("tmpl"); if (listener == null) { listener = new LZBindingListener(tempFileName); session.setAttribute("tmpl", listener); } else { listener.addTempFile(tempFileName); } } HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(url.getHost(), url.getPort(), url.getProtocol()); HttpClient htc = new HttpClient(); htc.setHostConfiguration(hostConfig); int rc = htc.executeMethod(getRequest); mLogger.debug("Response Status: " + rc); if (rc >= 400) { // respondWithError(req, res, "HTTP Status code: " + rc + " for url " + surl, rc); return null; } if (rc != HttpServletResponse.SC_NOT_MODIFIED) { FileOutputStream output = new FileOutputStream(tempFile); try { // FIXME:[2002-12-17 bloch] verify that the response body is XML FileUtils.sendToStream(getRequest.getResponseBodyAsStream(), output); // TODO: [2002-12-15 bloch] What to do with response headers? } catch (FileUtils.StreamWritingException e) { mLogger.warn( /* (non-Javadoc) * @i18n.test * @org-mes="StreamWritingException while sending error: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(), "051018-313", new Object[] { e.getMessage() })); } finally { FileUtils.close(output); } } return tempFileName; }