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

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

Introduction

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

Prototype

public HttpClientParams getParams() 

Source Link

Usage

From source file:com.zimbra.cs.client.LmcMessage.java

public byte[] downloadAttachment(String partNo, String baseURL, LmcSession session, String cookieDomain,
        int msTimeout) throws LmcSoapClientException, IOException {
    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread()
                + " LmcMessage.downloadAttachment session=null");

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    String url = baseURL + "?id=" + getID() + "&part=" + partNo;
    GetMethod get = new GetMethod(url);

    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        HttpState initialState = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            Cookie cookie = new Cookie(cookieDomain, ck.getKey(), ck.getValue(), "/", -1, false);
            initialState.addCookie(cookie);
        }/*from  w  w w  .j a  va  2  s. co m*/
        client.setState(initialState);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

    get.getParams().setSoTimeout(msTimeout);
    int statusCode = -1;
    try {
        statusCode = HttpClientUtil.executeMethod(client, get);

        // parse the response
        if (statusCode == 200) {
            return get.getResponseBody();
        } else {
            throw new LmcSoapClientException("Attachment download failed, status=" + statusCode);
        }
    } catch (IOException e) {
        System.err.println("Attachment download failed");
        e.printStackTrace();
        throw e;
    } finally {
        get.releaseConnection();
    }
}

From source file:au.com.redboxresearchdata.harvester.httpclient.BasicHttpClient.java

/**
 * Gets an HTTP client. If authentication is required, the authenticate()
 * method must be called prior to this method.
 * //from  w ww  .jav a2 s .c  om
 * @param auth set true to use authentication, false to skip authentication
 * @return an HTTP client
 */
public HttpClient getHttpClient(boolean auth) {
    HttpClient client = new HttpClient();
    try {
        URL url = new URL(baseUrl);
        //        log.info(baseUrl + "----------------------------1111------------");
        Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
        if (!proxy.type().equals(Proxy.Type.DIRECT)) {
            InetSocketAddress address = (InetSocketAddress) proxy.address();
            String proxyHost = address.getHostName();
            int proxyPort = address.getPort();
            client.getHostConfiguration().setProxy(proxyHost, proxyPort);
            //          log.trace("Using proxy {}:{}", proxyHost, proxyPort);
        }
    } catch (Exception e) {
        //    log.warn("Failed to get proxy settings: " + e.getMessage());
    }
    if (auth && credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
        //  log.trace("Credentials: username={}", credentials.getUserName());
    }
    return client;
}

From source file:com.serena.rlc.jenkins.plugins.rlcnotifier.RLCSite.java

public String executeJSONPut(URI uri, String putContents) throws Exception {
    String result = null;/*from w  ww.  j  a va  2 s.  com*/
    HttpClient httpClient = new HttpClient();

    if ("https".equalsIgnoreCase(uri.getScheme())) {
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory();
        Protocol https = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", https);
    }

    PutMethod method = new PutMethod(uri.toString());
    if (putContents != null)
        method.setRequestBody(putContents);
    method.setRequestHeader("Content-Type", "application/json");
    method.setRequestHeader("charset", "utf-8");
    try {
        HttpClientParams params = httpClient.getParams();
        params.setAuthenticationPreemptive(true);

        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, clientCredentials);

        int responseCode = httpClient.executeMethod(method);

        //if (responseCode < 200 || responseCode < 300) {
        if (responseCode != 200 && responseCode != 204) {
            throw new Exception("Serena RLC returned error code: " + responseCode);
        } else {
            result = method.getResponseBodyAsString();
        }
    } catch (Exception e) {
        throw new Exception("Error connecting to Serena RLC: " + e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return result;
}

From source file:com.serena.rlc.jenkins.plugins.rlcnotifier.RLCSite.java

public String executeJSONPost(URI uri, String postContents) throws Exception {
    String result = null;// w w w  . jav a 2s . c  om
    HttpClient httpClient = new HttpClient();

    if ("https".equalsIgnoreCase(uri.getScheme())) {
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory();
        Protocol https = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", https);
    }

    PostMethod method = new PostMethod(uri.toString());
    if (postContents != null)
        method.setRequestBody(postContents);
    method.setRequestHeader("Content-Type", "application/json");
    method.setRequestHeader("charset", "utf-8");
    try {
        HttpClientParams params = httpClient.getParams();
        params.setAuthenticationPreemptive(true);

        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, clientCredentials);

        int responseCode = httpClient.executeMethod(method);

        if (responseCode != 200) {
            throw new Exception("Serena RLC returned error code: " + responseCode);
        } else {
            result = method.getResponseBodyAsString();
        }
    } catch (Exception e) {
        throw new Exception("Error connecting to Serena RLC: " + e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return result;
}

From source file:edu.ku.brc.specify.utilapps.RegProcessor.java

/**
 * @param urlKey/*from  ww  w .  jav  a2  s . c  o m*/
 * @param inclDmp
 * @return
 */
public File getDataFromWeb(final String urlKey, final boolean inclDmp) {
    try {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter("http.useragent", RegisterSpecify.class.getName()); //$NON-NLS-1$

        String urlStr = UIRegistry.getResourceString(urlKey);

        PostMethod postMethod = new PostMethod(urlStr + (inclDmp ? "?dmp=1&" : ""));

        // connect to the server
        try {
            httpClient.executeMethod(postMethod);

            InputStream iStream = postMethod.getResponseBodyAsStream();

            File tempFile = File.createTempFile("web", "data");
            byte[] bytes = new byte[8196];

            PrintWriter pw = new PrintWriter(tempFile);
            int numBytes = 0;
            do {
                numBytes = iStream.read(bytes);
                if (numBytes > 0) {
                    pw.write(new String(bytes, 0, numBytes));
                }

            } while (numBytes > 0);

            pw.close();

            return tempFile;
        } catch (Exception e) {
            //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(RegProcessor.class, e);
            e.printStackTrace();
            throw new ConnectionException(e);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:com.zimbra.cs.account.ZimbraAuthToken.java

@Override
public void encode(HttpClient client, HttpMethod method, boolean isAdminReq, String cookieDomain)
        throws ServiceException {
    String origAuthData = getOrigAuthData();

    HttpState state = new HttpState();
    client.setState(state);// ww w. j av a 2  s.  c o  m

    state.addCookie(new org.apache.commons.httpclient.Cookie(cookieDomain,
            ZimbraCookie.authTokenCookieName(isAdminReq), origAuthData, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
}

From source file:com.googlecode.fascinator.indexer.SolrIndexer.java

/**
 * Initialize a Solr core object.//from   w  w w . j  av a  2s  .  co m
 * 
 * @param coreName : The core to initialize
 * @return SolrServer : The initialized core
 */
private SolrServer initCore(String coreName) {
    try {
        String uri = config.getString(null, "indexer", coreName, "uri");
        if (uri == null) {
            log.error("No URI provided for core: '{}'", coreName);
            return null;
        }
        URI solrUri = new URI(uri);
        CommonsHttpSolrServer thisCore = new CommonsHttpSolrServer(solrUri.toURL());
        String username = config.getString(null, "indexer", coreName, "username");
        String password = config.getString(null, "indexer", coreName, "password");
        usernameMap.put(coreName, username);
        passwordMap.put(coreName, password);
        if (username != null && password != null) {
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
            HttpClient hc = (thisCore).getHttpClient();
            hc.getParams().setAuthenticationPreemptive(true);
            hc.getState().setCredentials(AuthScope.ANY, credentials);
        }
        return thisCore;
    } catch (MalformedURLException mue) {
        log.error(coreName + " : Malformed URL", mue);
    } catch (URISyntaxException urise) {
        log.error(coreName + " : Invalid URI", urise);
    }
    return null;
}

From source file:com.urbancode.ds.jenkins.plugins.serenarapublisher.UrbanDeploySite.java

public String executeJSONPut(URI uri, String putContents) throws Exception {
    String result = null;// w  ww.  ja  va 2  s .  com
    HttpClient httpClient = new HttpClient();

    if ("https".equalsIgnoreCase(uri.getScheme())) {
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory();
        Protocol https = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", https);
    }

    PutMethod method = new PutMethod(uri.toString());
    setDirectSsoInteractionHeader(method);
    method.setRequestBody(putContents);
    method.setRequestHeader("Content-Type", "application/json");
    method.setRequestHeader("charset", "utf-8");
    try {
        HttpClientParams params = httpClient.getParams();
        params.setAuthenticationPreemptive(true);

        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, clientCredentials);

        int responseCode = httpClient.executeMethod(method);

        //if (responseCode < 200 || responseCode < 300) {
        if (responseCode != 200 && responseCode != 204) {
            throw new Exception("Serena DA returned error code: " + responseCode);
        } else {
            result = method.getResponseBodyAsString();
        }
    } catch (Exception e) {
        throw new Exception("Error connecting to SerenaRA: " + e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return result;
}

From source file:com.urbancode.ds.jenkins.plugins.serenarapublisher.UrbanDeploySite.java

public String executeJSONPost(URI uri, String postContents) throws Exception {
    String result = null;/*from  w w w .  ja  va  2s  .  co  m*/
    HttpClient httpClient = new HttpClient();

    if ("https".equalsIgnoreCase(uri.getScheme())) {
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory();
        Protocol https = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", https);
    }

    PostMethod method = new PostMethod(uri.toString());
    setDirectSsoInteractionHeader(method);
    method.setRequestBody(postContents);
    method.setRequestHeader("Content-Type", "application/json");
    method.setRequestHeader("charset", "utf-8");
    try {
        HttpClientParams params = httpClient.getParams();
        params.setAuthenticationPreemptive(true);

        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, clientCredentials);

        int responseCode = httpClient.executeMethod(method);

        if (responseCode != 200) {
            throw new Exception("SerenaRA returned error code: " + responseCode);
        } else {
            result = method.getResponseBodyAsString();
        }
    } catch (Exception e) {
        throw new Exception("Error connecting to Serena DA: " + e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return result;
}

From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java

/**
 * Logs in the given user with the given password.
 * /*from   ww w  .  java 2  s  .c  o m*/
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException
 */
@Deprecated
public String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = PropertyReader.getFrameworkUrl();
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    if (tokens.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");

    if (hostPort.countTokens() != NUMBER_OF_URL_TOKENS) {
        throw new IOException(
                "Url in the config file is in the wrong format, needs to be http://<host>:<port>");
    }
    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", userid);
    login.addParameter("j_password", password);

    client.executeMethod(login);

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

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod(LOGIN_URL);
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);

    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())));
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}