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.gs.jrpip.client.FastServletProxyFactory.java

public static Cookie[] requestNewSession(AuthenticatedUrl url) {
    CreateSessionRequest createSessionRequest = null;
    try {/*from ww  w. j  ava 2 s .com*/
        HttpClient httpClient = getHttpClient(url);
        createSessionRequest = new CreateSessionRequest(url.getPath());
        HttpMethodParams params = createSessionRequest.getParams();
        params.setSoTimeout(PING_TIMEOUT);
        httpClient.executeMethod(createSessionRequest);
        return httpClient.getState().getCookies();
    } catch (Exception e) {
        throw new RuntimeException("Failed to create session", e);
    } finally {
        if (createSessionRequest != null) {
            createSessionRequest.releaseConnection();
        }
    }
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

/**
 * Make the http request to the specified url
 * @return If returnArray is true, a byte array containing the response bytes,
 * if false, we return an ObjectArray with the first argument being an 
 * InputStream and the second being the GetMethod that was used to make the
 * request.  The GetMethod must have releaseConnection() called on it after
 * all of the InputStream has been read.
 *//* www.j a v a  2  s  .c  o  m*/
public static Object makeHttpRequest(String url, Credentials c, String realm, boolean returnArray) {
    GetMethod getMethod = new GetMethod(url);
    Object returnValue = null;
    HttpClient client;
    try {
        client = new HttpClient();
        if (c != null) {
            client.getParams().setAuthenticationPreemptive(true);
            //client.getState().set
            //client.getState().setCredentials(new HttpAuthRealm(null, realm), c);
            //client.getState().setCredentials(realm, null, c);
            client.getState().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), c);
        }
        int statusCode = -1;
        // We will retry up to 3 times.
        for (int attempt = 0; statusCode == -1 && attempt < 3; attempt++) {
            try {
                // execute the method.
                statusCode = client.executeMethod(getMethod);
            } catch (HttpRecoverableException e) {
                System.err.println("A recoverable exception occurred, retrying.  " + e.getMessage());
            } catch (IOException e) {
                System.err.println("Failed to download file.");
                e.printStackTrace();
                break;
            }
        }
        if (statusCode == HttpStatus.SC_OK) {
            if (returnArray) {
                returnValue = getMethod.getResponseBodyAsStream();
                InputStream stream = (InputStream) returnValue;
                byte[] bytes;
                long contentLength = getMethod.getResponseContentLength();
                if (contentLength >= 0) {
                    bytes = new byte[(int) contentLength];
                } else {
                    // it returned -1, so it doesn't know how long the
                    // length is.  We'll allocate a 5mb buffer in this case
                    bytes = new byte[MAX_BYTES];
                }
                int offset = 0;
                int nextByte = 0;
                try {
                    while ((nextByte = stream.read()) != -1) {
                        bytes[offset++] = (byte) nextByte;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        stream.close();
                    }
                }
                byte[] newBytes = new byte[offset];
                System.arraycopy(bytes, 0, newBytes, 0, offset);
                returnValue = newBytes;
                // make sure these get garbage collected
                bytes = null;
            } else {
                InputStream stream = getMethod.getResponseBodyAsStream();
                returnValue = new Object[] { stream, getMethod };
            }
        } else {
            System.err.println("bad status code is: " + statusCode);
            returnValue = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        try {
            getMethod.getResponseBody();
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            if (returnArray) {
                getMethod.releaseConnection();
            }
        }
        returnValue = null;
    } finally {
        if (returnArray) {
            getMethod.releaseConnection();
        }
    }
    return returnValue;
}

From source file:com.nokia.carbide.internal.bugreport.model.Communication.java

public static void setProxyData(HttpClient client, PostMethod postMethod) {
    URI uri = getURI(postMethod);
    if (uri == null) {
        return;/* w w w  .  j  ava2  s  .co  m*/
    }
    IProxyData proxyData = ProxyUtils.getProxyData(uri);
    if (proxyData == null) {
        return;
    }
    String host = proxyData.getHost();
    int port = proxyData.getPort();
    client.getHostConfiguration().setProxy(host, port);
    if (proxyData.isRequiresAuthentication()) {
        String userId = proxyData.getUserId();
        String password = proxyData.getPassword();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password);
        AuthScope authScope = new AuthScope(host, port);
        client.getState().setCredentials(authScope, credentials);
        postMethod.setDoAuthentication(true);
    }
}

From source file:de.mpg.imeji.presentation.util.Scripts.java

public static String login(String frameworkUrl, String userName, String password) throws Exception {
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");

    tokens.nextToken();/*from  ww w  . j a  v a  2 s.c  om*/
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");

    String host = hostPort.nextToken();
    int port = Integer.parseInt(hostPort.nextToken());

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userName);
    login.addParameter("j_password", password);

    client.executeMethod(login);
    //System.out.println("Login form post: " + login.getStatusLine().toString());

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod("/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);
    //System.out.println("Login second post: " + postMethod.getStatusLine().toString());

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
            //System.out.println("location: "+location);
            //System.out.println("handle: "+userHandle);
        }
    }

    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritApiUtil.java

@NotNull
private static HttpClient getHttpClient(@Nullable final String login, @Nullable final String password) {
    final HttpClient client = new HttpClient();
    HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
    params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)

    client.getParams().setContentCharset("UTF-8");
    // Configure proxySettings if it is required
    final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    if (proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) {
        client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
        if (proxySettings.PROXY_AUTHENTICATION) {
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword()));
        }/*from   w ww . j ava  2  s .  c om*/
    }
    if (login != null && password != null) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(login, password));
    }
    return client;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Set credentials on HttpClient instance.
 *
 * @param httpClient httpClient instance
 * @param userName   user name//from  w  ww .ja v a2  s  .  co  m
 * @param password   user password
 */
public static void setCredentials(HttpClient httpClient, String userName, String password) {
    // some Exchange servers redirect to a different host for freebusy, use wide auth scope
    AuthScope authScope = new AuthScope(null, -1);
    httpClient.getState().setCredentials(authScope, new NTCredentials(userName, password, "UNKNOWN", ""));
}

From source file:de.mpg.imeji.presentation.util.LoginHelper.java

/**
 * Get handle of System administrator of eSciDoc instance.
 * // w  w w  .j a  va2 s.co  m
 * @return
 */
//    public static String loginSystemAdmin()
//    {
//        String handle = null;
//        try
//        {
//            handle = login(PropertyReader.getProperty("framework.admin.username"),
//                    PropertyReader.getProperty("framework.admin.password"));
//        }
//        catch (Exception e)
//        {
//            sessionBean = (SessionBean)BeanHelper.getSessionBean(SessionBean.class);
//            BeanHelper
//                    .info(sessionBean.getLabel("error") + ", wrong administrator user. Check config file or FW: " + e);
//            logger.error("Error escidoc admin login", e);
//        }
//        return handle;
//    }

public static String login(String userName, String password) throws Exception {
    String frameworkUrl = PropertyReader.getProperty("escidoc.framework_access.framework.url");
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");
    String host = hostPort.nextToken();
    int port = 80;
    if (hostPort.hasMoreTokens()) {
        port = Integer.parseInt(hostPort.nextToken());
    }
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().closeIdleConnections(1000);
    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userName);
    login.addParameter("j_password", password);
    try {
        client.executeMethod(login);
    } catch (Exception e) {
        throw new RuntimeException("Error login in " + frameworkUrl + "  status: " + login.getStatusCode()
                + " - " + login.getStatusText());
    }
    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());
    Cookie sessionCookie = logoncookies[0];
    PostMethod postMethod = new PostMethod("/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);
    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + postMethod.getStatusCode());
    }
    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:fr.gouv.finances.dgfip.xemelios.common.NetAccess.java

public static HttpClient getHttpClient(PropertiesExpansion applicationProperties)
        throws DataConfigurationException {
    String proxyHost = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_SERVER);
    String proxyPort = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_PORT);
    String proxyUser = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_USER);
    String sTmp = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_PASSWD);
    String proxyPasswd = sTmp != null ? Scramble.unScramblePassword(sTmp) : null;
    int intProxyPort = 0;
    if (proxyPort != null) {
        try {//from  www . jav a  2  s .c  o m
            intProxyPort = Integer.parseInt(proxyPort);
        } catch (NumberFormatException nfEx) {
            throw new DataConfigurationException(proxyPort + " n'est pas un numro de port valide.");
        }
    }
    String domainName = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_DOMAIN);

    HttpClient client = new HttpClient();
    //client.getParams().setAuthenticationPreemptive(true);   // check use of this
    HostConfiguration hc = new HostConfiguration();
    if (proxyHost != null) {
        hc.setProxy(proxyHost, intProxyPort);
        client.setHostConfiguration(hc);
    }
    if (proxyUser != null) {
        Credentials creds = null;
        if (domainName != null && domainName.length() > 0) {
            String hostName = "127.0.0.1";
            try {
                InetAddress ip = InetAddress.getByName("127.0.0.1");
                hostName = ip.getHostName();
            } catch (Exception ex) {
                logger.error("", ex);
            }
            creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
        } else {
            creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
        }
        client.getState().setProxyCredentials(AuthScope.ANY, creds);
        //            client.getState().setProxyCredentials(AuthScope.ANY,new UsernamePasswordCredentials(proxyUser,proxyPasswd));
    }
    return client;
}

From source file:com.nokia.carbide.installpackages.InstallPackages.java

public static void setProxyData(HttpClient client, GetMethod getMethod) {
    java.net.URI uri = getURI(getMethod);
    if (uri == null)
        return;/* w w  w  . j  av  a2  s  . com*/
    IProxyData proxyData = ProxyUtils.getProxyData(uri);
    if (proxyData == null)
        return;
    String host = proxyData.getHost();
    int port = proxyData.getPort();
    client.getHostConfiguration().setProxy(host, port);
    if (proxyData.isRequiresAuthentication()) {
        String userId = proxyData.getUserId();
        String password = proxyData.getPassword();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password);
        AuthScope authScope = new AuthScope(host, port);
        client.getState().setCredentials(authScope, credentials);
        getMethod.setDoAuthentication(true);
    }
}

From source file:com.bbytes.zorba.messaging.rabbitmq.utils.HttpClientFactoryBean.java

public HttpClientFactoryBean(HttpClient httpClient, Credentials credentials) {
    this.httpClient = httpClient;
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
}