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

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

Introduction

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

Prototype

public void setProxy(String paramString, int paramInt)

Source Link

Usage

From source file:com.liferay.util.Http.java

public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException {

    byte[] byteArray = null;

    HttpMethod method = null;/* w  w  w .jav  a  2 s  .  co  m*/

    try {
        HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

        if (location == null) {
            return byteArray;
        } else if (!location.startsWith(HTTP_WITH_SLASH) && !location.startsWith(HTTPS_WITH_SLASH)) {

            location = HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfig = new HostConfiguration();

        hostConfig.setHost(new URI(location));

        if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) {
            hostConfig.setProxy(PROXY_HOST, PROXY_PORT);
        }

        client.setHostConfiguration(hostConfig);
        client.setConnectionTimeout(5000);
        client.setTimeout(5000);

        if (cookies != null && cookies.length > 0) {
            HttpState state = new HttpState();

            state.addCookies(cookies);
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);

            client.setState(state);
        }

        if (post) {
            method = new PostMethod(location);
        } else {
            method = new GetMethod(location);
        }

        method.setFollowRedirects(true);

        client.executeMethod(method);

        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            return URLtoByteArray(locationHeader.getValue(), cookies, post);
        }

        InputStream is = method.getResponseBodyAsStream();

        if (is != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] bytes = new byte[512];

            for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) {

                buffer.write(bytes, 0, i);
            }

            byteArray = buffer.toByteArray();

            is.close();
            buffer.close();
        }

        return byteArray;
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception e) {
            Logger.error(Http.class, e.getMessage(), e);
        }
    }
}

From source file:com.exalead.io.failover.MonitoredHttpConnectionManager.java

/**
 * Gets the host configuration for a connection.
 * @param conn the connection to get the configuration of
 * @return a new HostConfiguration//from w ww  .  jav a  2  s  . c  o  m
 */
static HostConfiguration rebuildConfigurationFromConnection(HttpConnection conn) {
    HostConfiguration connectionConfiguration = new HostConfiguration();
    connectionConfiguration.setHost(conn.getHost(), conn.getPort(), conn.getProtocol());
    if (conn.getLocalAddress() != null) {
        connectionConfiguration.setLocalAddress(conn.getLocalAddress());
    }
    if (conn.getProxyHost() != null) {
        connectionConfiguration.setProxy(conn.getProxyHost(), conn.getProxyPort());
    }
    return connectionConfiguration;
}

From source file:com.orange.mmp.net.http.HttpConnectionManager.java

public Connection getConnection() throws MMPNetException {
    SimpleHttpConnectionManager shcm = new SimpleHttpConnectionManager();

    HttpClientParams defaultHttpParams = new HttpClientParams();
    defaultHttpParams.setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    defaultHttpParams.setParameter(HttpConnectionParams.TCP_NODELAY, true);
    defaultHttpParams.setParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    defaultHttpParams.setParameter(HttpConnectionParams.SO_LINGER, 0);
    defaultHttpParams.setParameter(HttpClientParams.MAX_REDIRECTS, 3);
    defaultHttpParams.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, false);

    HttpClient httpClient2 = new HttpClient(defaultHttpParams, shcm);

    if (HttpConnectionManager.proxyHost != null) {
        defaultHttpParams.setParameter("http.route.default-proxy",
                new HttpHost(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort)); // TODO Host configuration !
        if (HttpConnectionManager.proxyHost != null/* && this.useProxy*/) {
            HostConfiguration config = new HostConfiguration();
            config.setProxy(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort);
            httpClient2.setHostConfiguration(config);
        } else {//from www  . j a  v  a 2s.  c o  m
            HostConfiguration config = new HostConfiguration();
            config.setProxyHost(null);
            httpClient2.setHostConfiguration(config);
        }
    }

    return new HttpConnection(httpClient2);
}

From source file:fr.dutra.confluence2wordpress.xmlrpc.CommonsXmlRpcTransportFactory.java

public CommonsXmlRpcTransportFactory(URL url, String proxyHost, int proxyPort, int maxConnections) {
    this.url = url;
    HostConfiguration hostConf = new HostConfiguration();
    hostConf.setHost(url.getHost(), url.getPort());
    if (proxyHost != null && proxyPort != -1) {
        hostConf.setProxy(proxyHost, proxyPort);
    }/*from  w ww. j  a  v  a2s. com*/
    HttpConnectionManagerParams connParam = new HttpConnectionManagerParams();
    connParam.setMaxConnectionsPerHost(hostConf, maxConnections);
    connParam.setMaxTotalConnections(maxConnections);
    MultiThreadedHttpConnectionManager conMgr = new MultiThreadedHttpConnectionManager();
    conMgr.setParams(connParam);
    client = new HttpClient(conMgr);
    client.setHostConfiguration(hostConf);
}

From source file:com.apatar.core.ApatarHttpClient.java

private String sendHttpQuery(HttpMethod method) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    HostConfiguration hostConfig = client.getHostConfiguration();
    if (isUseProxy) {
        hostConfig.setProxy(host, port);

        if (userName != null && !userName.equals("")) {
            client.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials(userName, password, "", ""));
        }//  w  ww  .j a va 2 s  .c  o  m
    }

    client.executeMethod(method);

    return method.getResponseBodyAsString();
}

From source file:com.eviware.soapui.impl.wsdl.support.http.ProxyUtils.java

public static HostConfiguration initProxySettings(Settings settings, HttpState httpState,
        HostConfiguration hostConfiguration, String urlString, PropertyExpansionContext context) {
    boolean enabled = proxyEnabled;

    // check system properties first
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if (proxyHost == null && enabled)
        proxyHost = PropertyExpander.expandProperties(context, settings.getString(ProxySettings.HOST, ""));
    if (proxyPort == null && proxyHost != null && enabled)
        proxyPort = PropertyExpander.expandProperties(context, settings.getString(ProxySettings.PORT, ""));

    if (!StringUtils.isNullOrEmpty(proxyHost) && !StringUtils.isNullOrEmpty(proxyPort)) {
        // check excludes
        String[] excludes = PropertyExpander
                .expandProperties(context, settings.getString(ProxySettings.EXCLUDES, "")).split(",");

        try {/*  w  w  w. j a  v a2s.com*/
            URL url = new URL(urlString);

            if (!excludes(excludes, url.getHost(), url.getPort())) {
                hostConfiguration.setProxy(proxyHost, Integer.parseInt(proxyPort));

                String proxyUsername = PropertyExpander.expandProperties(context,
                        settings.getString(ProxySettings.USERNAME, null));
                String proxyPassword = PropertyExpander.expandProperties(context,
                        settings.getString(ProxySettings.PASSWORD, null));

                if (proxyUsername != null && proxyPassword != null) {
                    Credentials proxyCreds = new UsernamePasswordCredentials(proxyUsername,
                            proxyPassword == null ? "" : proxyPassword);

                    // check for nt-username
                    int ix = proxyUsername.indexOf('\\');
                    if (ix > 0) {
                        String domain = proxyUsername.substring(0, ix);
                        if (proxyUsername.length() > ix + 1) {
                            String user = proxyUsername.substring(ix + 1);
                            proxyCreds = new NTCredentials(user, proxyPassword, proxyHost, domain);
                        }
                    }

                    httpState.setProxyCredentials(AuthScope.ANY, proxyCreds);
                }
            }
        } catch (MalformedURLException e) {
            SoapUI.logError(e);
        }
    }

    return hostConfiguration;
}

From source file:dk.netarkivet.viewerproxy.ViewerProxyTester.java

@Before
public void setUp() throws Exception {
    rs.setUp();/*www. j  a v a  2  s . com*/
    JMSConnectionMockupMQ.useJMSConnectionMockupMQ();
    ChannelsTesterHelper.resetChannels();
    Settings.set(CommonSettings.REMOTE_FILE_CLASS, "dk.netarkivet.common.distribute.TestRemoteFile");

    TestFileUtils.copyDirectoryNonCVS(TestInfo.ORIGINALS_DIR, TestInfo.WORKING_DIR);
    TestFileUtils.copyDirectoryNonCVS(TestInfo.ORIGINALS_DIR, TestInfo.ARCHIVE_DIR);

    Settings.set(CommonSettings.CACHE_DIR, new File(TestInfo.WORKING_DIR, "cachedir").getAbsolutePath());
    // Set up an HTTP client that can send commands to our proxy;
    int httpPort = Integer.parseInt(Settings.get(CommonSettings.HTTP_PORT_NUMBER));
    httpClient = new HttpClient();
    HostConfiguration hc = new HostConfiguration();
    String hostName = "localhost";
    hc.setProxy(hostName, httpPort);
    httpClient.setHostConfiguration(hc);
}

From source file:de.pdark.dsmp.ProxyDownload.java

/**
 * Do the download.//from w ww . ja  v a 2  s  .  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 DSMP config");
    }

    // If there is a status file in the cache, return it instead of trying it again
    // As usual with caches, this one is a key area which will always cause
    // trouble.
    // TODO There should be a simple way to get rid of the cached statuses
    // TODO Maybe retry a download after a certain time?
    File statusFile = new File(dest.getAbsolutePath() + ".status");
    if (statusFile.exists()) {
        try {
            FileReader r = new FileReader(statusFile);
            char[] buffer = new char[(int) statusFile.length()];
            int len = r.read(buffer);
            r.close();
            String status = new String(buffer, 0, len);
            throw new DownloadFailed(status);
        } catch (IOException e) {
            log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
        }
    }

    mkdirs();

    HttpClient client = new HttpClient();

    String msg = "";
    if (config.useProxy(url)) {
        Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(),
                config.getProxyPassword());
        AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(config.getProxyHost(), config.getProxyPort());
        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 (0 == 1 && log.isDebugEnabled()) {
            Header[] header = get.getResponseHeaders();
            for (Header aHeader : header)
                log.debug(aHeader.toString().trim());
        }

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

        if (status != HttpStatus.SC_OK) {
            // Remember "File not found"
            if (status == HttpStatus.SC_NOT_FOUND) {
                try {
                    FileWriter w = new FileWriter(statusFile);
                    w.write(get.getStatusLine().toString());
                    w.close();
                } catch (IOException e) {
                    log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
                }
            }
            throw new DownloadFailed(get);
        }

        File dl = new File(dest.getAbsolutePath() + ".new");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        IOUtils.copy(get.getResponseBodyAsStream(), out);
        out.close();

        File bak = new File(dest.getAbsolutePath() + ".bak");
        if (bak.exists())
            bak.delete();
        if (dest.exists())
            dest.renameTo(bak);
        dl.renameTo(dest);
    } finally {
        get.releaseConnection();
    }
}

From source file:it.unibz.instasearch.jobs.CheckUpdatesJob.java

/**
 * @param httpClient//  ww w  .  ja  v  a  2 s  .  c  o  m
 * @param versionCheckUrl
 * @throws URISyntaxException 
 */
private void configureProxy(HttpClient httpClient, String versionCheckUrl) throws URISyntaxException {
    IProxyService proxyService = InstaSearchPlugin.getDefault().getProxyService();

    if (proxyService != null && proxyService.isProxiesEnabled()) {
        URI uri = new URI(versionCheckUrl);
        final IProxyData[] proxiesData = proxyService.select(uri);

        IProxyData proxy = null;
        for (IProxyData proxyData : proxiesData) {
            if (proxyData.getType().equals(IProxyData.HTTP_PROXY_TYPE)) {
                proxy = proxyData;
                break;
            }
        }

        if (proxy == null)
            return;

        HostConfiguration config = httpClient.getHostConfiguration();
        config.setProxy(proxy.getHost(), proxy.getPort());

        if (proxy.isRequiresAuthentication()) {
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUserId(), proxy.getPassword());
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            httpClient.getState().setProxyCredentials(authScope, credentials);
        }
    }
}

From source file:com.jaspersoft.studio.server.util.HttpUtils31.java

public static void setupProxy(HttpClient c, URL arg2, HostConfiguration config) {
    IProxyService proxyService = getProxyService();
    if (proxyService == null)
        return;// ww  w. j ava2s  .c om
    IProxyData[] proxyDataForHost;
    try {
        proxyDataForHost = proxyService.select(arg2.toURI());
        for (IProxyData data : proxyDataForHost) {
            if (data.isRequiresAuthentication()) {
                String userId = data.getUserId();
                Credentials proxyCred = new UsernamePasswordCredentials(userId, data.getPassword());
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userId.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userId.substring(0, domainIndex);
                    if (userId.length() > domainIndex + 1) {
                        String user = userId.substring(domainIndex + 1);
                        proxyCred = new NTCredentials(user, data.getPassword(), data.getHost(), domain);
                    }
                }
                c.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
            }
            config.setProxy(data.getHost(), data.getPort());
        }
        // Close the service and close the service tracker
        proxyService = null;
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}