Example usage for org.apache.commons.httpclient HostConfiguration setHost

List of usage examples for org.apache.commons.httpclient HostConfiguration setHost

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HostConfiguration setHost.

Prototype

public void setHost(URI paramURI) 

Source Link

Usage

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Simple channel validation - ensures URL
 * is valid, XML document is returned, and
 * document has an rss root element with a 
 * version, or rdf root element, /*from  w  w  w  . j  av  a 2 s .  c o m*/
 */
public static boolean isValid(URL url) throws HttpUserException {
    boolean valid = false;
    try {
        //         System.setProperty("networkaddress.cache.ttl", "0");

        HttpClient client = new HttpClient();
        ChannelManager.getChannelManager().configureHttpClient(client);
        if (url.getUserInfo() != null) {
            client.getState().setCredentials(null, null,
                    new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
        }

        String urlString = url.toString();
        HttpMethod method = null;

        int count = 0;
        HttpResult result = null;
        int statusCode = HttpStatus.SC_OK;
        boolean redirected = false;
        do {
            method = new GetMethod(urlString);
            method.setRequestHeader("User-agent", AppConstants.getUserAgent());
            method.setRequestHeader("Accept-Encoding", "gzip");
            method.setFollowRedirects(false);
            method.setDoAuthentication(true);

            HostConfiguration hostConfiguration = client.getHostConfiguration();
            URI hostURI = new URI(urlString);
            hostConfiguration.setHost(hostURI);

            result = executeHttpRequest(client, hostConfiguration, method);
            statusCode = result.getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statusCode == HttpStatus.SC_SEE_OTHER
                    || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirected = true;
                // Resolve against current URI - may be a relative URI
                try {
                    urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                } catch (URISyntaxException use) {
                    // Fall back to just using location from result
                    urlString = result.getLocation();
                }
            } else {
                redirected = false;
            }

            //            method.getResponseBody();
            //            method.releaseConnection();
            count++;
        } while (count < 5 && redirected);

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (statusCode == HttpStatus.SC_OK) {
            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);

            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();
            Document rssDoc = db.parse(bis);
            Element rootElm = rssDoc.getDocumentElement();

            for (int i = 0; i < parsers.length; i++) {
                if (parsers[i].isParsable(rootElm)) {
                    valid = true;
                    break;
                }
            }
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            throw new HttpUserException(statusCode);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new HttpUserException(statusCode);
        }

    } catch (URIException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valid;
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaUri() throws Exception {
    HostConfiguration hostConfig = createHostConfiguration();

    URI uri = new URI("http://www.mulesoft.org:8080", false);
    hostConfig.setHost(uri);

    assertMockSocketFactory(hostConfig);
    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertEquals(8080, hostConfig.getPort());
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaUriWithDifferentProtocol() throws Exception {
    new DifferentProtocolTemplate() {
        protected void doTest() throws Exception {
            HostConfiguration hostConfig = createHostConfiguration();

            URI uri = new URI("httpx://www.mulesoft.org:8080", false);
            hostConfig.setHost(uri);

            assertTrue(hostConfig.getProtocol().getSocketFactory() instanceof DefaultProtocolSocketFactory);
            assertEquals("www.mulesoft.org", hostConfig.getHost());
            assertEquals(8080, hostConfig.getPort());
        }/*from   w  w  w. j av a  2  s  .  c  o m*/
    }.test();
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaHttpHost() {
    HostConfiguration hostConfig = createHostConfiguration();

    HttpHost host = new HttpHost("www.mulesoft.org", 8080);
    hostConfig.setHost(host);

    assertMockSocketFactory(hostConfig);
    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertEquals(8080, hostConfig.getPort());
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaHost() {
    HostConfiguration hostConfig = createHostConfiguration();

    hostConfig.setHost("www.mulesoft.org");

    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertMockSocketFactory(hostConfig);
}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * @param since last modified time to use
 * @param req//  w  w  w  .  j ava  2  s.  co m
 * @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 www .  j ava 2  s.  co m
    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.openmicroscopy.shoola.svc.transport.BasicChannel.java

/**
 * Creates a <code>HttpClient</code> to communicate.
 * @see HttpChannel#getCommunicationLink()
 *//* w ww.  j a  v  a  2 s .com*/
protected HttpClient getCommunicationLink() {
    HostConfiguration cfg = new HostConfiguration();
    cfg.setHost(serverURL);
    String proxyHost = System.getProperty(HttpChannel.PROXY_HOST);
    String proxyPort = System.getProperty(HttpChannel.PROXY_PORT);
    if (proxyHost != null && proxyPort != null) {
        int port = Integer.parseInt(proxyPort);
        cfg.setProxy(proxyHost, port);
    }

    HttpClient channel = new HttpClient();
    channel.setHostConfiguration(cfg);
    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(connTimeout);
    channel.setParams(params);
    return channel;
}

From source file:org.pengyou.client.lib.DavSession.java

/**
 * Get a <code>HttpClient</code> instance.
 * This method returns a new client instance, when reset is true.
 *
 * @param reset The reset flag to represent whether the saved information
 *              is used or not./*from ww  w.  ja  v a  2 s  .co m*/
 * @return An instance of <code>HttpClient</code>.
 * @exception IOException
 */
public HttpClient getSessionInstance(boolean reset) throws IOException {

    if (reset || client == null) {
        HttpURL httpURL = context.getHttpURL();
        client = new HttpClient();
        // Set a state which allows lock tracking
        client.setState(new WebdavState());
        HostConfiguration hostConfig = client.getHostConfiguration();
        hostConfig.setHost(httpURL);
        if (context.getProxyHost() != null && context.getProxyPort() > 0)
            hostConfig.setProxy(context.getProxyHost(), context.getProxyPort());

        if (hostCredentials == null) {
            String userName = httpURL.getUser();
            if (userName != null && userName.length() > 0) {
                hostCredentials = new UsernamePasswordCredentials(userName, httpURL.getPassword());
            }
        }

        if (hostCredentials != null) {
            HttpState clientState = client.getState();
            clientState.setCredentials(null, httpURL.getHost(), hostCredentials);
            clientState.setAuthenticationPreemptive(true);
        }

        if (proxyCredentials != null) {
            client.getState().setProxyCredentials(null, context.getProxyHost(), proxyCredentials);
        }
    }

    return client;
}

From source file:org.portletbridge.portlet.DefaultHttpClientTemplate.java

public Object service(HttpMethodBase method, HttpClientState state, HttpClientCallback callback)
        throws ResourceException {
    try {//w ww. jav a  2 s .  c om
        HostConfiguration hostConfiguration = new HostConfiguration();

        if (state.getProxyHost() != null && state.getProxyHost().trim().length() > 0) {
            hostConfiguration.setProxy(state.getProxyHost(), state.getProxyPort());
        }
        hostConfiguration.setHost(method.getURI());
        int statusCode = httpClient.executeMethod(hostConfiguration, method, state.getHttpState());
        return callback.doInHttpClient(statusCode, method);
    } catch (ResourceException e) {
        throw e;
    } catch (Throwable e) {
        throw new ResourceException("error.httpclient", e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}