Example usage for org.apache.commons.httpclient HttpClient setHostConfiguration

List of usage examples for org.apache.commons.httpclient HttpClient setHostConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient setHostConfiguration.

Prototype

public void setHostConfiguration(HostConfiguration paramHostConfiguration)

Source Link

Usage

From source file:org.fao.geonet.lib.NetLib.java

/** Setup proxy for http client
  *//* w  w  w . java  2 s .c  o m*/
public void setupProxy(SettingManager sm, HttpClient client) {
    boolean enabled = sm.getValueAsBool(ENABLED, false);
    String host = sm.getValue(HOST);
    String port = sm.getValue(PORT);
    String username = sm.getValue(USERNAME);
    String password = sm.getValue(PASSWORD);

    if (enabled) {
        if (!Lib.type.isInteger(port)) {
            Log.error(Geonet.GEONETWORK, "Proxy port is not an integer : " + port);
        } else {
            HostConfiguration config = client.getHostConfiguration();
            if (config == null)
                config = new HostConfiguration();
            config.setProxy(host, Integer.parseInt(port));
            client.setHostConfiguration(config);

            if (username.trim().length() != 0) {
                Credentials cred = new UsernamePasswordCredentials(username, password);
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

                client.getState().setProxyCredentials(scope, cred);
            }
            List authPrefs = new ArrayList(2);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.BASIC);
            // This will exclude the NTLM authentication scheme
            client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }
    }
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

/**
 * Queries the igniterealtime.org server for new server and plugin updates.
 *
 * @param notificationsEnabled true if admins will be notified when new updates are found.
 * @throws Exception if some error happens during the query.
 *//*from w w w  .  j a v  a  2s .co  m*/
public synchronized void checkForServerUpdate(boolean notificationsEnabled) throws Exception {
    // Get the XML request to include in the HTTP request
    String requestXML = getServerUpdateRequest();
    // Send the request to the server
    HttpClient httpClient = new HttpClient();
    // Check if a proxy should be used
    if (isUsingProxy()) {
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(getProxyHost(), getProxyPort());
        httpClient.setHostConfiguration(hc);
    }
    PostMethod postMethod = new PostMethod(updateServiceURL);
    NameValuePair[] data = { new NameValuePair("type", "update"), new NameValuePair("query", requestXML) };
    postMethod.setRequestBody(data);
    if (httpClient.executeMethod(postMethod) == 200) {
        // Process answer from the server
        String responseBody = postMethod.getResponseBodyAsString();
        processServerUpdateResponse(responseBody, notificationsEnabled);
    }
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

public synchronized void checkForPluginsUpdates(boolean notificationsEnabled) throws Exception {
    // Get the XML request to include in the HTTP request
    String requestXML = getAvailablePluginsUpdateRequest();
    // Send the request to the server
    HttpClient httpClient = new HttpClient();
    // Check if a proxy should be used
    if (isUsingProxy()) {
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(getProxyHost(), getProxyPort());
        httpClient.setHostConfiguration(hc);
    }/* w  ww  .  j  a v  a  2s  .  co m*/
    PostMethod postMethod = new PostMethod(updateServiceURL);
    NameValuePair[] data = { new NameValuePair("type", "available"), new NameValuePair("query", requestXML) };
    postMethod.setRequestBody(data);
    if (httpClient.executeMethod(postMethod) == 200) {
        // Process answer from the server
        String responseBody = postMethod.getResponseBodyAsString();
        processAvailablePluginsResponse(responseBody, notificationsEnabled);
    }
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

/**
 * Download and install latest version of plugin.
 *
 * @param url the URL of the latest version of the plugin.
 * @return true if the plugin was successfully downloaded and installed.
 *//*from   w  w w .  j a v  a 2s  .c  o m*/
public boolean downloadPlugin(String url) {
    boolean installed = false;
    // Download and install new version of plugin
    HttpClient httpClient = new HttpClient();
    // Check if a proxy should be used
    if (isUsingProxy()) {
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(getProxyHost(), getProxyPort());
        httpClient.setHostConfiguration(hc);
    }
    GetMethod getMethod = new GetMethod(url);
    //execute the method
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode == 200) {
            //get the resonse as an InputStream
            InputStream in = getMethod.getResponseBodyAsStream();
            String pluginFilename = url.substring(url.lastIndexOf("/") + 1);
            installed = XMPPServer.getInstance().getPluginManager().installPlugin(in, pluginFilename);
            in.close();
            if (installed) {
                // Remove the plugin from the list of plugins to update
                for (Update update : pluginUpdates) {
                    if (update.getURL().equals(url)) {
                        update.setDownloaded(true);
                    }
                }
                // Save response in a file for later retrieval
                saveLatestServerInfo();
            }
        }
    } catch (IOException e) {
        Log.warn("Error downloading new plugin version", e);
    }
    return installed;
}

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

public void configureHttpClient(HttpClient client) {
    client.setHostConfiguration(hostConfig);

    if ((proxyUserID != null && proxyUserID.length() > 0)
            || (proxyPassword != null && proxyPassword.length() > 0)) {
        client.getState().setProxyCredentials(null, null,
                new UsernamePasswordCredentials(proxyUserID, (proxyPassword == null) ? "" : proxyPassword));
    } else {//from   www  .  j  ava  2s  . c  om
        client.getState().setProxyCredentials(null, null, null);
    }
}

From source file:org.moxie.proxy.connection.ProxyDownload.java

/**
 * Do the download.//from  w  w  w  . j  ava  2s. c  o  m
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in Moxie Proxy config");
    }

    HttpClient client = new HttpClient();
    String userAgent = config.getUserAgent();
    if (userAgent != null && userAgent.trim().length() > 0) {
        client.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
    }

    String msg = "";
    if (config.useProxy(url)) {
        Proxy proxy = config.getProxy(url);
        Credentials defaultcreds = new UsernamePasswordCredentials(proxy.username, proxy.password);
        AuthScope scope = new AuthScope(proxy.host, proxy.port, AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(proxy.host, proxy.port);
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (status == 1 && log.isLoggable(Level.FINE)) {
            Header[] header = get.getResponseHeaders();
            for (int i = 0; i < header.length; i++)
                log.fine(header[i].toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            throw new DownloadFailed(get);
        }

        // Make sure the temporary file is created in
        // the destination folder, otherwise
        // dl.renameTo(dest) might not work
        // for example if you have a separate /tmp partition
        // on Linux
        File destinationFolder = dest.getParentFile();
        dest.getParentFile().mkdirs();
        File dl = File.createTempFile("moxie-", ".tmp", destinationFolder);
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        copy(get.getResponseBodyAsStream(), out);
        out.close();

        // create folder structure after successful download
        // - no, we create it before the download!
        //dest.getParentFile().mkdirs();

        if (dest.exists()) {
            dest.delete();
        }
        dl.renameTo(dest);

        // preserve last-modified, if possible
        try {
            Header lastModified = get.getResponseHeader("Last-Modified");
            if (lastModified != null) {
                Date date = DateUtil.parseDate(lastModified.getValue());
                dest.setLastModified(date.getTime());
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "could not parse \"last-modified\" for " + url, e);
        }
    } finally {
        get.releaseConnection();
    }
}

From source file:org.moxie.proxy.connection.ProxyHead.java

/**
 * Do the download (of the headers)./*from w  ww. java 2 s . c  om*/
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in Moxie Proxy config");
    }

    HttpClient client = new HttpClient();
    String userAgent = config.getUserAgent();
    if (userAgent != null && userAgent.trim().length() > 0) {
        client.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
    }

    String msg = "";
    if (config.useProxy(url)) {
        Proxy proxy = config.getProxy(url);
        Credentials defaultcreds = new UsernamePasswordCredentials(proxy.username, proxy.password);
        AuthScope scope = new AuthScope(proxy.host, proxy.port, AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(proxy.host, proxy.port);
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + url);

    MyHeadMethod head = new MyHeadMethod(url.toString());
    head.setFollowRedirects(true);
    try {
        int status = client.executeMethod(head);

        log.info("Download status: " + status);
        this.header = head.getResponseHeaders();
        this.statusLine = head.getStatusLine().toString();
        this.responseBody = head.getResponseBody();
        if (status == 1 && log.isLoggable(Level.FINE)) {
            for (int i = 0; i < header.length; i++)
                log.fine(header[i].toString().trim());
        }

        log.info("Content: " + valueOf(head.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(head.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            throw new DownloadFailed(head);
        }

    } finally {
        head.releaseConnection();
    }
}

From source file:org.n52.oxf.util.IOHelper.java

public static InputStream sendGetMessage(String serviceURL, String queryString) throws IOException {
    InputStream is = null;// w  w  w.j a v a 2 s.c  o m

    HttpClient httpClient = new HttpClient();
    httpClient.setHostConfiguration(getHostConfiguration(new URL(serviceURL)));
    GetMethod method = new GetMethod(serviceURL);

    method.setQueryString(queryString);

    httpClient.executeMethod(method);

    LOGGER.info("GET-method sended to: " + method.getURI());

    is = method.getResponseBodyAsStream();

    return is;
}

From source file:org.n52.oxf.util.IOHelper.java

/**
 * sends a POST-request using org.apache.commons.httpclient.HttpClient.
 * /*from w  ww  .ja  v  a 2 s .co  m*/
 * @param serviceURL
 * @param request
 * @return
 */
public static InputStream sendPostMessage(String serviceURL, String request) throws IOException {

    InputStream is = null;

    HttpClient httpClient = new HttpClient();
    PostMethod method = new PostMethod(serviceURL);

    method.setRequestEntity(new StringRequestEntity(request, "text/xml", "UTF-8"));

    HostConfiguration hostConfig = getHostConfiguration(new URL(serviceURL));
    httpClient.setHostConfiguration(hostConfig);
    httpClient.executeMethod(method);

    LOGGER.info("POST-request sent to: " + method.getURI());
    LOGGER.info("Sent request was: " + request);

    is = method.getResponseBodyAsStream();

    return is;
}

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;
}