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

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

Introduction

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

Prototype

public HttpState getState()

Source Link

Usage

From source file:com.headwire.aem.tooling.intellij.util.BundleStateHelper.java

private static HttpClient getHttpClient(String user, String password) {
    final HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    // authentication stuff
    client.getParams().setAuthenticationPreemptive(true);
    Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);

    return client;
}

From source file:com.zimbra.common.httpclient.HttpClientUtil.java

public static int executeMethod(HttpClient client, HttpMethod method, HttpState state)
        throws HttpException, IOException {
    ProxyHostConfiguration proxyConfig = HttpProxyConfig.getProxyConfig(client.getHostConfiguration(),
            method.getURI().toString());
    if (proxyConfig != null && proxyConfig.getUsername() != null && proxyConfig.getPassword() != null) {
        if (state == null) {
            state = client.getState();
            if (state == null) {
                state = new HttpState();
            }//from  www.j  a v  a  2s  . co  m
        }
        state.setProxyCredentials(new AuthScope(proxyConfig.getHost(), proxyConfig.getPort()),
                new UsernamePasswordCredentials(proxyConfig.getUsername(), proxyConfig.getPassword()));
    }
    return client.executeMethod(proxyConfig, method, state);
}

From source file:jp.go.nict.langrid.management.logic.service.ProcessDeployer.java

static InputStream openStream(URL url, String userName, String password) throws IOException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    client.setHttpConnectionManager(manager);
    GetMethod m = new GetMethod(url.getFile());
    if ((userName != null) && (userName.length() > 0)) {
        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        m.setDoAuthentication(true);//w  w w. j av  a2  s . c  o m
    }
    try {
        client.executeMethod(m);
        if (m.getStatusCode() != 200) {
            throw new IOException("failed to get vaild http response: " + m.getStatusCode());
        }
        return new ByteArrayInputStream(StreamUtil.readAsBytes(m.getResponseBodyAsStream()));
    } finally {
        manager.shutdown();
    }
}

From source file:com.collabnet.tracker.common.httpClient.TrackerHttpSender.java

public static void setupHttpClient(HttpClient client, String repositoryUrl, String user, String password) {

    setupHttpClientParams(client, null);

    if (user != null && password != null) {
        AuthScope authScope = new AuthScope(getDomain(repositoryUrl), getPort(repositoryUrl),
                AuthScope.ANY_REALM);/*from  w ww. j a  v a2s .  c  o  m*/
        try {
            client.getState().setCredentials(authScope,
                    getCredentials(user, password, InetAddress.getLocalHost()));
        } catch (UnknownHostException e) {
            client.getState().setCredentials(authScope, getCredentials(user, password, null));
        }
    }

    if (isRepositoryHttps(repositoryUrl)) {
        Protocol acceptAllSsl = new Protocol("https",
                (ProtocolSocketFactory) SslProtocolSocketFactory.getInstance(), getPort(repositoryUrl));
        client.getHostConfiguration().setHost(getDomain(repositoryUrl), getPort(repositoryUrl), acceptAllSsl);
        Protocol.registerProtocol("https", acceptAllSsl);
    } else {
        client.getHostConfiguration().setHost(getDomain(repositoryUrl), getPort(repositoryUrl));
    }
}

From source file:net.sourceforge.jcctray.model.HTTPCruise.java

private static HttpClient getClient(Host host) {
    SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
    HttpConnectionManagerParams connParams = new HttpConnectionManagerParams();
    connParams.setConnectionTimeout(JCCTraySettings.getInstance().getInt(ISettingsConstants.HTTP_TIMEOUT));
    connParams.setSoTimeout(JCCTraySettings.getInstance().getInt(ISettingsConstants.HTTP_TIMEOUT));
    connectionManager.setParams(connParams);
    HttpClient client = new HttpClient(connectionManager);

    client.getParams().setAuthenticationPreemptive(true);
    if (!StringUtils.isEmptyOrNull(host.getHostName()) && !StringUtils.isEmptyOrNull(host.getPassword())) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(host.getUsername(),
                host.getPassword());//from   ww w .j  a  v a 2  s.  c o  m
        client.getState().setCredentials(new AuthScope(null, -1, null, null), credentials);
    }

    return client;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

private static void setCredentials(HttpClient client, HttpMethod httpMethod, String username, String password) {
    // set Username and Password
    if (username != null) {
        if (password == null)
            password = "";
        client.getState().setCredentials(null, null, new UsernamePasswordCredentials(username, password));
        httpMethod.setDoAuthentication(true);
    }//  w ww . ja  va 2s  . c o  m
}

From source file:PublisherUtil.java

/**
 * Publishes a list of files and a datasource to the server with basic authentication to the server
 * /*from   www  .jav  a 2 s. c o m*/
 * @param publishURL
 *          The URL of the Pentaho server
 * @param publishPath
 *          The path in the solution to place the files
 * @param publishFiles
 *          Array of File objects to post to the server
 * @param dataSource
 *          The datasource to publish to the server
 * @param publishPassword
 *          The publishing password for the server
 * @param serverUserid
 *          The userid to authenticate to the server
 * @param serverPassword
 *          The password to authenticate with the server
 * @param overwrite
 *          Whether the server should overwrite the file if it exists already
 * @param mkdirs
 *          Whether the server should create any missing folders on the publish path
 * @return Server response as a string
* @throws Exception 
 */
public static String publish(final String publishURL, final String publishPath, final File publishFiles[],
        final String publishPassword, final String serverUserid, final String serverPassword,
        final boolean overwrite, final boolean mkdirs) throws Exception {
    int status = -1;
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "warn");//$NON-NLS-1$ //$NON-NLS-2$
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn");//$NON-NLS-1$ //$NON-NLS-2$

    String fullURL = null;
    try {
        fullURL = publishURL + "?publishPath=" + URLEncoder.encode(publishPath, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        fullURL = publishURL + "?publishPath=" + publishPath;
        System.out.println("Erro de publicao na classe publisher!" + e);
        // throw new Exception("Erro de publicao na classe publisher!" + e);
    }
    if (publishPassword == null) {
        throw new IllegalArgumentException("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED"); //$NON-NLS-1$
        // throw new IllegalArgumentException(Messages.getErrorString("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED")); //$NON-NLS-1$
    }

    fullURL += "&publishKey=" + PublisherUtil.getPasswordKey(publishPassword); //$NON-NLS-1$
    fullURL += "&overwrite=" + overwrite; //$NON-NLS-1$
    fullURL += "&mkdirs=" + mkdirs; //$NON-NLS-1$

    PostMethod filePost = new PostMethod(fullURL);

    Part[] parts = new Part[publishFiles.length];
    for (int i = 0; i < publishFiles.length; i++) {
        try {
            File file = publishFiles[i];
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            String reportNameEncoded = (URLEncoder.encode(file.getName(), "UTF-8"));
            ByteArrayPartSource source = new ByteArrayPartSource(reportNameEncoded, out.toByteArray());
            parts[i] = new FilePart(reportNameEncoded, source, FilePart.DEFAULT_CONTENT_TYPE, "UTF-8");
        } catch (Exception e) {
            PublisherUtil.logger.error(null, e);
            throw new Exception("Erro de publicao na classe publisher!" + e);
        }
    }

    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();

    try {
        if ((serverUserid != null) && (serverUserid.length() > 0) && (serverPassword != null)
                && (serverPassword.length() > 0)) {
            Credentials creds = new UsernamePasswordCredentials(serverUserid, serverPassword);
            client.getState().setCredentials(AuthScope.ANY, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }
        status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            String postResult = filePost.getResponseBodyAsString();

            if (postResult != null) {
                try {
                    return postResult.trim(); // +" - "+Integer.parseInt(postResult.trim());
                } catch (NumberFormatException e) {
                    PublisherUtil.logger.error(null, e);
                    // throw new Exception("Erro de publicao na classe publisher!" + e + " " +PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS);
                    return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS;
                }
            }
        } else if (status == HttpStatus.SC_UNAUTHORIZED) {
            return "" + PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS;
        }
    } catch (HttpException e) {
        PublisherUtil.logger.error(null, e);
        // throw new Exception("Erro de publicao na classe publisher!" + e );
    } catch (IOException e) {
        PublisherUtil.logger.error(null, e);
        // throw new Exception("Erro de publicao na classe publisher!" + e );
    }
    // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$
    return "" + PublisherUtil.FILE_ADD_FAILED;
}

From source file:com.cloud.utils.net.HTTPUtils.java

/**
 * @param username/* ww  w  .ja v  a  2s.  c o m*/
 * @param password
 * @param httpClient
 */
public static void setCredentials(String username, String password, HttpClient httpClient) {
    if (username != null && password != null && httpClient != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Setting credentials with username " + username + " for host "
                    + httpClient.getHostConfiguration().getHost() + ":"
                    + httpClient.getHostConfiguration().getPort());
        }

        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(
                new AuthScope(httpClient.getHostConfiguration().getHost(),
                        httpClient.getHostConfiguration().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
    }
}

From source file:com.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {/*from  w  w  w  . j  ava 2  s . co m*/
        System.err.println("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        System.err.println("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        System.err.println("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        System.err.println(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:com.cloud.utils.UriUtils.java

public static InputStream getInputStreamFromUrl(String url, String user, String password) {

    try {//from  ww  w  . ja v  a 2 s  .  c  om
        Pair<String, Integer> hostAndPort = validateUrl(url);
        HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
        if ((user != null) && (password != null)) {
            httpclient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
            httpclient.getState().setCredentials(
                    new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM),
                    defaultcreds);
            s_logger.info("Added username=" + user + ", password=" + password + "for host "
                    + hostAndPort.first() + ":" + hostAndPort.second());
        }
        // Execute the method.
        GetMethod method = new GetMethod(url);
        int statusCode = httpclient.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }

        return method.getResponseBodyAsStream();
    } catch (Exception ex) {
        s_logger.error("Failed to read from URL: " + url);
        return null;
    }
}