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:org.pentaho.di.trans.steps.http.HTTP.java

private Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException {
    String url = determineUrl(rowMeta, rowData);
    try {//from  w ww. j  a  v a 2  s .  c  o m
        if (isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "HTTP.Log.Connecting", url));
        }

        // Prepare HTTP get
        //
        HttpClient httpclient = SlaveConnectionManager.getInstance().createHttpClient();
        HttpMethod method = new GetMethod(url);

        // Set timeout
        if (data.realConnectionTimeout > -1) {
            httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(data.realConnectionTimeout);
        }
        if (data.realSocketTimeout > -1) {
            httpclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout);
        }

        if (!Const.isEmpty(data.realHttpLogin)) {
            httpclient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin,
                    data.realHttpPassword);
            httpclient.getState().setCredentials(AuthScope.ANY, defaultcreds);
        }

        HostConfiguration hostConfiguration = new HostConfiguration();
        if (!Const.isEmpty(data.realProxyHost)) {
            hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort);
        }

        // Add Custom HTTP headers
        if (data.useHeaderParameters) {
            for (int i = 0; i < data.header_parameters_nrs.length; i++) {
                method.addRequestHeader(data.headerParameters[i].getName(),
                        data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
                if (isDebug()) {
                    log.logDebug(BaseMessages.getString(PKG, "HTTPDialog.Log.HeaderValue",
                            data.headerParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
                }
            }
        }

        InputStreamReader inputStreamReader = null;
        Object[] newRow = null;
        if (rowData != null) {
            newRow = rowData.clone();
        }
        // Execute request
        //
        try {
            // used for calculating the responseTime
            long startTime = System.currentTimeMillis();

            int statusCode = httpclient.executeMethod(hostConfiguration, method);

            // calculate the responseTime
            long responseTime = System.currentTimeMillis() - startTime;
            if (log.isDetailed()) {
                log.logDetailed(BaseMessages.getString(PKG, "HTTP.Log.ResponseTime", responseTime, url));
            }

            String body = null;
            // The status code
            if (isDebug()) {
                logDebug(BaseMessages.getString(PKG, "HTTP.Log.ResponseStatusCode", "" + statusCode));
            }

            if (statusCode != -1) {
                if (statusCode == 204) {
                    body = "";
                } else {
                    // if the response is not 401: HTTP Authentication required
                    if (statusCode != 401) {
                        // guess encoding
                        //
                        String encoding = meta.getEncoding();

                        // Try to determine the encoding from the Content-Type value
                        //
                        if (Const.isEmpty(encoding)) {
                            String contentType = method.getResponseHeader("Content-Type").getValue();
                            if (contentType != null && contentType.contains("charset")) {
                                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "")
                                        .replace("\"", "").trim();
                            }
                        }

                        if (isDebug()) {
                            log.logDebug(toString(),
                                    BaseMessages.getString(PKG, "HTTP.Log.ResponseHeaderEncoding", encoding));
                        }

                        // the response
                        if (!Const.isEmpty(encoding)) {
                            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(),
                                    encoding);
                        } else {
                            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream());
                        }
                        StringBuffer bodyBuffer = new StringBuffer();

                        int c;
                        while ((c = inputStreamReader.read()) != -1) {
                            bodyBuffer.append((char) c);
                        }

                        inputStreamReader.close();

                        body = bodyBuffer.toString();
                        if (isDebug()) {
                            logDebug("Response body: " + body);
                        }

                    } else { // the status is a 401
                        throw new KettleStepException(
                                BaseMessages.getString(PKG, "HTTP.Exception.Authentication", data.realUrl));

                    }
                }
            }

            int returnFieldsOffset = rowMeta.size();
            if (!Const.isEmpty(meta.getFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
                returnFieldsOffset++;
            }

            if (!Const.isEmpty(meta.getResultCodeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
                returnFieldsOffset++;
            }
            if (!Const.isEmpty(meta.getResponseTimeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
            }

        } finally {
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            // Release current connection to the connection pool once you are done
            method.releaseConnection();
            if (data.realcloseIdleConnectionsTime > -1) {
                httpclient.getHttpConnectionManager().closeIdleConnections(data.realcloseIdleConnectionsTime);
            }
        }
        return newRow;
    } catch (UnknownHostException uhe) {
        throw new KettleException(
                BaseMessages.getString(PKG, "HTTP.Error.UnknownHostException", uhe.getMessage()));
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "HTTP.Log.UnableGetResult", url), e);
    }
}

From source file:org.pentaho.di.trans.steps.httppost.HTTPPOST.java

private Object[] callHTTPPOST(Object[] rowData) throws KettleException {
    // get dynamic url ?
    if (meta.isUrlInField()) {
        data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField);
    }//www  .j a v a 2  s  .com

    FileInputStream fis = null;
    try {
        if (isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "HTTPPOST.Log.ConnectingToURL", data.realUrl));
        }

        // Prepare HTTP POST
        //
        HttpClient HTTPPOSTclient = SlaveConnectionManager.getInstance().createHttpClient();
        PostMethod post = new PostMethod(data.realUrl);
        // post.setFollowRedirects(false);

        // Set timeout
        if (data.realConnectionTimeout > -1) {
            HTTPPOSTclient.getHttpConnectionManager().getParams()
                    .setConnectionTimeout(data.realConnectionTimeout);
        }
        if (data.realSocketTimeout > -1) {
            HTTPPOSTclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout);
        }

        if (!Const.isEmpty(data.realHttpLogin)) {
            HTTPPOSTclient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin,
                    data.realHttpPassword);
            HTTPPOSTclient.getState().setCredentials(AuthScope.ANY, defaultcreds);
        }

        HostConfiguration hostConfiguration = new HostConfiguration();
        if (!Const.isEmpty(data.realProxyHost)) {
            hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort);
        }
        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed by the POSTMethod
        if (!data.contentTypeHeaderOverwrite) { // can be overwritten now
            if (Const.isEmpty(data.realEncoding)) {
                post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML);
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE,
                            CONTENT_TYPE_TEXT_XML));
                }
            } else {
                post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding);
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE,
                            CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding));
                }
            }
        }

        // HEADER PARAMETERS
        if (data.useHeaderParameters) {
            // set header parameters that we want to send
            for (int i = 0; i < data.header_parameters_nrs.length; i++) {
                post.addRequestHeader(data.headerParameters[i].getName(),
                        data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue",
                            data.headerParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
                }
            }
        }

        // BODY PARAMETERS
        if (data.useBodyParameters) {
            // set body parameters that we want to send
            for (int i = 0; i < data.body_parameters_nrs.length; i++) {
                data.bodyParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i]));
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.BodyValue",
                            data.bodyParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i])));
                }
            }
            post.setRequestBody(data.bodyParameters);
        }

        // QUERY PARAMETERS
        if (data.useQueryParameters) {
            for (int i = 0; i < data.query_parameters_nrs.length; i++) {
                data.queryParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i]));
                if (isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.QueryValue",
                            data.queryParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i])));
                }
            }
            post.setQueryString(data.queryParameters);
        }

        // Set request entity?
        if (data.indexOfRequestEntity >= 0) {
            String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity);
            // Request content will be retrieved directly
            // from the input stream
            // Per default, the request content needs to be buffered
            // in order to determine its length.
            // Request body buffering can be avoided when
            // content length is explicitly specified

            if (meta.isPostAFile()) {
                File input = new File(tmp);
                fis = new FileInputStream(input);
                post.setRequestEntity(new InputStreamRequestEntity(fis, input.length()));
            } else {
                if ((data.realEncoding != null) && (data.realEncoding.length() > 0)) {
                    post.setRequestEntity(new InputStreamRequestEntity(
                            new ByteArrayInputStream(tmp.getBytes(data.realEncoding)), tmp.length()));
                } else {
                    post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()),
                            tmp.length()));
                }
            }
        }

        // Execute request
        //
        InputStreamReader inputStreamReader = null;
        Object[] newRow = null;
        if (rowData != null) {
            newRow = rowData.clone();
        }
        try {
            // used for calculating the responseTime
            long startTime = System.currentTimeMillis();

            // Execute the POST method
            int statusCode = HTTPPOSTclient.executeMethod(hostConfiguration, post);

            // calculate the responseTime
            long responseTime = System.currentTimeMillis() - startTime;

            if (isDetailed()) {
                logDetailed(
                        BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseTime", responseTime, data.realUrl));
            }

            // Display status code
            if (isDebug()) {
                logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseCode", String.valueOf(statusCode)));
            }
            String body = null;
            if (statusCode != -1) {
                if (statusCode == 204) {
                    body = "";
                } else {
                    // if the response is not 401: HTTP Authentication required
                    if (statusCode != 401) {

                        // Use request encoding if specified in component to avoid strange response encodings
                        // See PDI-3815
                        String encoding = data.realEncoding;

                        // Try to determine the encoding from the Content-Type value
                        //
                        if (Const.isEmpty(encoding)) {
                            String contentType = post.getResponseHeader("Content-Type").getValue();
                            if (contentType != null && contentType.contains("charset")) {
                                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "")
                                        .replace("\"", "").trim();
                            }
                        }

                        // Get the response, but only specify encoding if we've got one
                        // otherwise the default charset ISO-8859-1 is used by HttpClient
                        if (Const.isEmpty(encoding)) {
                            if (isDebug()) {
                                logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", "ISO-8859-1"));
                            }
                            inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream());
                        } else {
                            if (isDebug()) {
                                logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", encoding));
                            }
                            inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream(), encoding);
                        }

                        StringBuffer bodyBuffer = new StringBuffer();

                        int c;
                        while ((c = inputStreamReader.read()) != -1) {
                            bodyBuffer.append((char) c);
                        }
                        inputStreamReader.close();

                        // Display response
                        body = bodyBuffer.toString();

                        if (isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseBody", body));
                        }
                    } else { // the status is a 401
                        throw new KettleStepException(
                                BaseMessages.getString(PKG, "HTTPPOST.Exception.Authentication", data.realUrl));

                    }
                }
            }
            int returnFieldsOffset = data.inputRowMeta.size();
            if (!Const.isEmpty(meta.getFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
                returnFieldsOffset++;
            }

            if (!Const.isEmpty(meta.getResultCodeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
                returnFieldsOffset++;
            }
            if (!Const.isEmpty(meta.getResponseTimeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
            }
        } finally {
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
            if (data.realcloseIdleConnectionsTime > -1) {
                HTTPPOSTclient.getHttpConnectionManager()
                        .closeIdleConnections(data.realcloseIdleConnectionsTime);
            }
        }
        return newRow;
    } catch (UnknownHostException uhe) {
        throw new KettleException(
                BaseMessages.getString(PKG, "HTTPPOST.Error.UnknownHostException", uhe.getMessage()));
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "HTTPPOST.Error.CanNotReadURL", data.realUrl), e);

    } finally {
        if (fis != null) {
            BaseStep.closeQuietly(fis);
        }
    }
}

From source file:org.pentaho.di.trans.steps.webservices.WebService.java

private HttpClient getHttpClient(HostConfiguration vHostConfiguration) {
    HttpClient vHttpClient = SlaveConnectionManager.getInstance().createHttpClient();

    String httpLogin = environmentSubstitute(meta.getHttpLogin());
    if (httpLogin != null && !"".equals(httpLogin)) {
        vHttpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(httpLogin,
                environmentSubstitute(meta.getHttpPassword()));
        vHttpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
    }//from   ww w  .jav  a2s  .  com

    String proxyHost = environmentSubstitute(meta.getProxyHost());
    if (proxyHost != null && !"".equals(proxyHost)) {
        vHostConfiguration.setProxy(proxyHost, Const.toInt(environmentSubstitute(meta.getProxyPort()), 8080));
    }
    return vHttpClient;
}

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

public Object service(HttpMethodBase method, HttpClientState state, HttpClientCallback callback)
        throws ResourceException {
    try {/* w w  w  .j  a  v a  2s .  co m*/
        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();
    }
}

From source file:org.red5.server.service.Installer.java

/**
 * Returns a Map containing all of the application wars in the snapshot repository.
 * /*from w  w  w. j  a va  2s  .  c om*/
 * @return async message
 */
public AsyncMessage getApplicationList() {
    AcknowledgeMessage result = new AcknowledgeMessage();

    // create a singular HttpClient object
    HttpClient client = new HttpClient();

    // set the proxy (WT)
    // test if we received variables on the commandline
    if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) {
        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(System.getProperty("http.proxyHost").toString(),
                Integer.parseInt(System.getProperty("http.proxyPort")));
    }

    // establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    //get the params for the client
    HttpClientParams params = client.getParams();
    params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
    //get registry file
    HttpMethod method = new GetMethod(applicationRepositoryUrl + "registry-0.9.xml");
    //follow any 302's although there shouldnt be any
    method.setFollowRedirects(true);
    // execute the method
    try {
        IConnection conn = Red5.getConnectionLocal();
        int code = client.executeMethod(method);
        log.debug("HTTP response code: {}", code);
        String xml = method.getResponseBodyAsString();
        log.trace("Response: {}", xml);
        //prepare response for flex         
        result.body = xml;
        result.clientId = conn.getClient().getId();
        result.messageId = UUID.randomUUID().toString();
        result.timestamp = System.currentTimeMillis();
        //send the servers java version so the correct apps are installed
        String javaVersion = System.getProperty("java.version");
        if (!ServiceUtils.invokeOnConnection(conn, "onJavaVersion", new Object[] { javaVersion })) {
            log.warn("Client call to onJavaVersion failed");
        }
    } catch (HttpException he) {
        log.error("Http error connecting to {}", applicationRepositoryUrl, he);
    } catch (IOException ioe) {
        log.error("Unable to connect to {}", applicationRepositoryUrl, ioe);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return result;
}

From source file:org.red5.server.service.Installer.java

/**
 * Installs a given application./* w  w  w  . j  a v a  2 s  .  co  m*/
 * 
 * @param applicationWarName app war name
 * @return true if installed; false otherwise
 */
public boolean install(String applicationWarName) {
    IConnection conn = Red5.getConnectionLocal();

    boolean result = false;

    //strip everything except the applications name
    String application = applicationWarName.substring(0, applicationWarName.indexOf('-'));
    log.debug("Application name: {}", application);

    //get webapp location
    String webappsDir = System.getProperty("red5.webapp.root");
    log.debug("Webapp folder: {}", webappsDir);

    //setup context
    String contextPath = '/' + application;
    String contextDir = webappsDir + contextPath;

    //verify this is a unique app
    File appDir = new File(webappsDir, application);
    if (appDir.exists()) {
        if (appDir.isDirectory()) {
            log.debug("Application directory exists");
        } else {
            log.warn("Application destination is not a directory");
        }

        ServiceUtils.invokeOnConnection(conn, "onAlert",
                new Object[] { String.format(
                        "Application %s already installed, please un-install before attempting another install",
                        application) });
    } else {
        //use the system temp directory for moving files around
        String srcDir = System.getProperty("java.io.tmpdir");
        log.debug("Source directory: {}", srcDir);
        //look for archive containing application (war, zip, etc..)
        File dir = new File(srcDir);
        if (!dir.exists()) {
            log.warn("Source directory not found");
            //use another directory
            dir = new File(System.getProperty("red5.root"), "/webapps/installer/WEB-INF/cache");
            if (!dir.exists()) {
                if (dir.mkdirs()) {
                    log.info("Installer cache directory created");
                }
            }
        } else {
            if (!dir.isDirectory()) {
                log.warn("Source directory is not a directory");
            }
        }
        //get a list of temp files
        File[] files = dir.listFiles();
        for (File f : files) {
            String fileName = f.getName();
            if (fileName.equals(applicationWarName)) {
                log.debug("File found matching application name");
                result = true;
                break;
            }
        }
        dir = null;

        //if the file was not found then download it
        if (!result) {
            // create a singular HttpClient object
            HttpClient client = new HttpClient();

            // set the proxy (WT)
            if ((System.getProperty("http.proxyHost") != null)
                    && (System.getProperty("http.proxyPort") != null)) {
                HostConfiguration config = client.getHostConfiguration();
                config.setProxy(System.getProperty("http.proxyHost").toString(),
                        Integer.parseInt(System.getProperty("http.proxyPort")));
            }

            // establish a connection within 5 seconds
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            //get the params for the client
            HttpClientParams params = client.getParams();
            params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
            params.setParameter(HttpMethodParams.STRICT_TRANSFER_ENCODING, Boolean.TRUE);

            //try the wav version first
            HttpMethod method = new GetMethod(applicationRepositoryUrl + applicationWarName);
            //we dont want any transformation - RFC2616
            method.addRequestHeader("Accept-Encoding", "identity");
            //follow any 302's although there shouldnt be any
            method.setFollowRedirects(true);
            FileOutputStream fos = null;
            // execute the method
            try {
                int code = client.executeMethod(method);
                log.debug("HTTP response code: {}", code);
                //create output file
                fos = new FileOutputStream(srcDir + '/' + applicationWarName);
                log.debug("Writing response to {}/{}", srcDir, applicationWarName);

                // have to receive the response as a byte array.  This has the advantage of writing to the filesystem
                // faster and it also works on macs ;)
                byte[] buf = method.getResponseBody();
                fos.write(buf);
                fos.flush();

                result = true;
            } catch (HttpException he) {
                log.error("Http error connecting to {}", applicationRepositoryUrl, he);
            } catch (IOException ioe) {
                log.error("Unable to connect to {}", applicationRepositoryUrl, ioe);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                    }
                }
                if (method != null) {
                    method.releaseConnection();
                }
            }
        }

        //if we've found or downloaded the war
        if (result) {
            //get the webapp loader
            LoaderMBean loader = getLoader();
            if (loader != null) {
                //un-archive it to app dir
                FileUtil.unzip(srcDir + '/' + applicationWarName, contextDir);
                //load and start the context
                loader.startWebApplication(application);
            } else {
                //just copy the war to the webapps dir
                try {
                    FileUtil.moveFile(srcDir + '/' + applicationWarName,
                            webappsDir + '/' + application + ".war");
                    ServiceUtils.invokeOnConnection(conn, "onAlert",
                            new Object[] { String.format(
                                    "Application %s will not be available until container is restarted",
                                    application) });
                } catch (IOException e) {
                }
            }
        }

        ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format("Application %s was %s",
                application, (result ? "installed" : "not installed")) });

    }
    appDir = null;

    return result;
}

From source file:org.rhq.enterprise.server.plugins.jboss.software.JBossSoftwareContentSourceAdapter.java

/**
 * If proxy information was specified, configures the client to use it.
 *
 * @param client client being used in the invocation
 *///from  w  w  w  . ja  va2 s . c  o m
private void configureProxy(HttpClient client) {
    // If a proxy URL was specified, configure the client for proxy support
    if (proxyUrl != null) {
        log.debug("Configuring feed for proxy. URL: " + proxyUrl + ", Port: " + proxyPort);
        HostConfiguration hostConfiguration = client.getHostConfiguration();
        hostConfiguration.setProxy(proxyUrl, proxyPort);

        // If a proxy username was specified, indicate it as the proxy credentials
        if (proxyUsername != null) {
            log.debug("Configuring feed for authenticating proxy. User: " + proxyUsername);
            AuthScope proxyAuthScope = new AuthScope(proxyUrl, proxyPort, AuthScope.ANY_REALM);
            Credentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
            client.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }
}

From source file:org.rhq.enterprise.server.plugins.url.HttpProvider.java

/**
 * If proxy information was specified, configures the client to use it.
 *
 * @param client client being used in the invocation
 *//* w ww  . jav  a2  s. c o  m*/
protected void configureProxy(HttpClient client) {
    if (this.proxyUrl != null) {
        if (log.isDebugEnabled()) {
            log.debug("Configuring HTTP proxy. url [" + this.proxyUrl + "]; port [" + this.proxyPort + "]");
        }

        HostConfiguration hostConfiguration = client.getHostConfiguration();
        hostConfiguration.setProxy(this.proxyUrl, this.proxyPort);

        // If a proxy username was specified, indicate it as the proxy credentials
        if (this.proxyUsername != null) {
            if (log.isDebugEnabled()) {
                log.debug("Configuring feed for authenticating proxy. proxy-user: " + this.proxyUsername);
            }
            AuthScope proxyAuthScope = new AuthScope(this.proxyUrl, this.proxyPort, AuthScope.ANY_REALM);
            Credentials proxyCredentials = new UsernamePasswordCredentials(this.proxyUsername,
                    this.proxyPassword);
            client.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }

    return;
}

From source file:org.scohen.juploadr.upload.HttpClientFactory.java

public static HttpClient getHttpClient(CommunityAccount account) {
    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    Protocol http;//from   w  ww. j a v  a  2s .  c  o m
    if (account.isBandwidthLimited()) {
        http = new Protocol(HTTP, new BandwidthLimitingProtocolSocketFactory(account.getBandwidth()), 80);
    } else {
        http = new Protocol(HTTP, new DefaultProtocolSocketFactory(), 80);
    }

    Protocol.registerProtocol(HTTP, http);
    NetActivator activator = NetActivator.getDefault();
    IProxyService proxyService = activator.getProxyService();
    String home = ((IConfigurationElement) account.getConfiguration().getParent()).getAttribute("home"); //$NON-NLS-1$
    home = Core.furnishWebUrl(home);
    IProxyData proxyData = null;
    try {
        IProxyData[] select = proxyService.select(new URI(home));
        if (select.length > 0)
            proxyData = select[0];
    } catch (URISyntaxException e) {
        activator.logError(Messages.HttpClientFactory_bad_uri_for_proxy, e);
    } finally {
        activator.ungetProxyService(proxyService);
    }
    if (proxyData != null && proxyData.getHost() != null) {
        String proxyHost = proxyData.getHost();
        String proxyPassword = proxyData.getPassword();
        String proxyUsername = proxyData.getUserId();
        int proxyPort = proxyData.getPort();
        HostConfiguration hc = client.getHostConfiguration();
        if (proxyPort < 0)
            hc.setHost(proxyHost);
        else
            hc.setProxy(proxyHost, proxyPort);
        if (proxyData.isRequiresAuthentication() && proxyUsername.length() > 0) {
            Credentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
            client.getParams().setAuthenticationPreemptive(true);
            AuthScope scope = new AuthScope(proxyHost, proxyPort);
            client.getState().setProxyCredentials(scope, creds);
        }
    }
    client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
    client.getHttpConnectionManager().getParams().setSoTimeout(60000);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
    return client;
}

From source file:org.smartfrog.projects.alpine.transport.http.ProxySettings.java

/**
 * configure an HTTP client from the settinsg
 *
 * @param client/* www .j a  v  a 2s  .c  o m*/
 */
public void configureClient(HttpClient client) {
    if (isEnabled()) {
        HostConfiguration hostConfiguration = client.getHostConfiguration();
        hostConfiguration.setProxy(proxyHost, proxyPort);
        if (isAuthenticating()) {
            client.getState().setProxyCredentials(proxyRealm, proxyHost,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }
}