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:org.artifactory.cli.rest.RestClient.java

/**
 * Returnes an HTTP client object with the given configurations
 *
 * @param url         Target URL//www.ja  v a2s  . c o m
 * @param timeout     Request timeout
 * @param credentials For authentication
 * @return HttpClient - Configured client
 * @throws Exception
 */
private static HttpClient getHttpClient(String url, int timeout, Credentials credentials) {
    HttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
    HttpConnectionManagerParams connectionManagerParams = connectionManager.getParams();
    //Set the socket connection timeout
    connectionManagerParams.setConnectionTimeout(3000);
    HttpClient client = new HttpClient(connectionManager);
    HttpClientParams clientParams = client.getParams();
    //Set the socket data timeout
    int to = 60000;
    if (timeout > 0) {
        to = timeout;
    }
    clientParams.setSoTimeout(to);

    if (credentials != null) {
        String host;
        try {
            host = new URL(url).getHost();
        } catch (MalformedURLException mue) {
            throw new RemoteCommandException("\nAn error has occurred while trying to resolve the given url: "
                    + url + "\n" + mue.getMessage());
        }
        clientParams.setAuthenticationPreemptive(true);
        AuthScope scope = new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        client.getState().setCredentials(scope, credentials);
    }
    return client;
}

From source file:org.artifactory.repo.HttpRepoTest.java

@Test
public void testProxyRemoteAuthAndMultihome() {
    ProxyDescriptor proxyDescriptor = new ProxyDescriptor();
    proxyDescriptor.setHost("proxyHost");
    proxyDescriptor.setUsername("proxy-username");
    proxyDescriptor.setPassword("proxy-password");

    HttpRepoDescriptor httpRepoDescriptor = new HttpRepoDescriptor();
    httpRepoDescriptor.setUrl("http://test");

    httpRepoDescriptor.setProxy(proxyDescriptor);

    httpRepoDescriptor.setUsername("repo-username");
    httpRepoDescriptor.setPassword("repo-password");

    httpRepoDescriptor.setLocalAddress("0.0.0.0");

    HttpRepo httpRepo = new HttpRepo(httpRepoDescriptor, internalRepoService, false, null);
    HttpClient client = httpRepo.createHttpClient();

    Credentials proxyCredentials = client.getState().getProxyCredentials(AuthScope.ANY);
    Assert.assertNotNull(proxyCredentials);
    Assert.assertTrue(proxyCredentials instanceof UsernamePasswordCredentials,
            "proxyCredentials are of the wrong class");
    Assert.assertEquals(((UsernamePasswordCredentials) proxyCredentials).getUserName(), "proxy-username");
    Assert.assertEquals(((UsernamePasswordCredentials) proxyCredentials).getPassword(), "proxy-password");

    Credentials repoCredentials = client.getState()
            .getCredentials(new AuthScope("test", AuthScope.ANY_PORT, AuthScope.ANY_REALM));
    Assert.assertNotNull(repoCredentials);
    Assert.assertTrue(repoCredentials instanceof UsernamePasswordCredentials,
            "repoCredentials are of the wrong class");
    Assert.assertEquals(((UsernamePasswordCredentials) repoCredentials).getUserName(), "repo-username");
    Assert.assertEquals(((UsernamePasswordCredentials) repoCredentials).getPassword(), "repo-password");

    Assert.assertEquals(client.getHostConfiguration().getLocalAddress().getHostAddress(), "0.0.0.0");
}

From source file:org.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java

public <T> ListenableFuture<T> execute(Request request, AsyncHandler<T> handler) throws IOException {
    if (isClose.get()) {
        throw new IOException("Closed");
    }//from w  w w  .j  a v a 2s . com

    if (ResumableAsyncHandler.class.isAssignableFrom(handler.getClass())) {
        request = ResumableAsyncHandler.class.cast(handler).adjustRequestRange(request);
    }

    if (config.getMaxTotalConnections() > -1 && (maxConnections.get() + 1) > config.getMaxTotalConnections()) {
        throw new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
    }

    if (idleConnectionTimeoutThread != null) {
        idleConnectionTimeoutThread.shutdown();
        idleConnectionTimeoutThread = null;
    }

    int requestTimeout = AsyncHttpProviderUtils.requestTimeout(config, request);
    if (config.getIdleConnectionTimeoutInMs() > 0 && requestTimeout != -1
            && requestTimeout < config.getIdleConnectionTimeoutInMs()) {
        idleConnectionTimeoutThread = new IdleConnectionTimeoutThread();
        idleConnectionTimeoutThread.setConnectionTimeout(config.getIdleConnectionTimeoutInMs());
        idleConnectionTimeoutThread.addConnectionManager(connectionManager);
        idleConnectionTimeoutThread.start();
    }

    HttpClient httpClient = new HttpClient(params, connectionManager);

    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
    if (realm != null) {
        httpClient.getParams().setAuthenticationPreemptive(realm.getUsePreemptiveAuth());
        Credentials defaultcreds = new UsernamePasswordCredentials(realm.getPrincipal(), realm.getPassword());
        httpClient.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
    }

    HttpMethodBase method = createMethod(httpClient, request);
    ApacheResponseFuture<T> f = new ApacheResponseFuture<T>(handler, requestTimeout, request, method);
    f.touch();

    f.setInnerFuture(config.executorService()
            .submit(new ApacheClientRunnable<T>(request, handler, method, f, httpClient)));
    maxConnections.incrementAndGet();
    return f;
}

From source file:org.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;//  w  w  w  . j  ava  2 s . c om
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        String expect = request.getHeaders().getFirstValue("Expect");
        if (expect != null && expect.equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    Collection<Cookie> cookies = request.getCookies();
    if (isNonEmpty(cookies)) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    String ua = request.getHeaders().getFirstValue("User-Agent");
    if (ua != null) {
        method.setRequestHeader("User-Agent", ua);
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class, config));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:org.biomart.martservice.MartServiceUtils.java

/**
 * //from   w  w  w  . j a  v a 2s  . co m
 * @param client
 */
public static void setProxy(HttpClient client) {
    String host = System.getProperty("http.proxyHost");
    String port = System.getProperty("http.proxyPort");
    String user = System.getProperty("http.proxyUser");
    String password = System.getProperty("http.proxyPassword");

    if (host != null && port != null) {
        try {
            int portInteger = Integer.parseInt(port);
            client.getHostConfiguration().setProxy(host, portInteger);
            if (user != null && password != null) {
                client.getState().setProxyCredentials(new AuthScope(host, portInteger),
                        new UsernamePasswordCredentials(user, password));
            }
        } catch (NumberFormatException e) {
            logger.error("Proxy port not an integer", e);
        }
    }
}

From source file:org.bonitasoft.connectors.drools.common.DroolsConnector.java

private HttpClient getHttpClient() {
    final HttpClient httpClient = new HttpClient();
    // set proxy//from   ww w. j  a v a  2  s .com
    if (proxyHost != null && proxyPort != 0) {
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
    }
    // set proxy username & password
    if (proxyPassword != null && proxyUsername != null) {
        final Credentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
        httpClient.getState().setProxyCredentials(AuthScope.ANY, creds);
    }
    // set username & password
    if (username != null && password != null) {
        final Credentials creds = new UsernamePasswordCredentials(username, password);
        httpClient.getState().setCredentials(AuthScope.ANY, creds);
    }
    // set connection/read timeout
    final HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    if (connectionTimeout != 0) {
        managerParams.setConnectionTimeout(connectionTimeout);
    }
    if (readTimeout != 0) {
        managerParams.setSoTimeout(readTimeout);
    }
    return httpClient;
}

From source file:org.bonitasoft.connectors.xwiki.common.XWikiRestClient.java

/**
 * Update an XWiki MetaData using REST//from  w w  w  .  ja va  2s .com
 * @throws IOException 
 * @throws HttpException 
 */
@SuppressWarnings("deprecation")
public boolean updateMetadata(String wikiName, String spaceName, String pageName, String className,
        String propertyName, String propertyValue, XWikiConnector conn) throws HttpException, IOException {
    try {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("updateMetadata wikiName=" + wikiName + " spaceName=" + spaceName + " pageName="
                    + pageName + " className=" + className + " propertyName=" + propertyName + " value="
                    + propertyValue);
        }

        String uri = server + "/xwiki/rest/wikis/" + wikiName + "/spaces/" + spaceName + "/pages/" + pageName
                + "/objects/" + className + "/0/properties/" + propertyName;
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("PUT " + uri);
        }

        HttpClient httpClient = new HttpClient();
        JAXBContext context = JAXBContext.newInstance("org.xwiki.rest.model.jaxb");
        Unmarshaller unmarshaller = context.createUnmarshaller();

        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        httpClient.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);

        PutMethod putMethod = new PutMethod(uri);
        putMethod.addRequestHeader("Accept", "application/xml");
        putMethod.setRequestHeader("Content-Type", "text/plain");
        putMethod.setRequestBody(propertyValue);
        httpClient.executeMethod(putMethod);

        Object result = "";
        String returnString = putMethod.getResponseBodyAsString();
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("HTTP Result: " + returnString);
        }
        conn.setResponse(returnString);
        try {
            Property prop = (Property) unmarshaller.unmarshal(new StreamSource(new StringReader(returnString)));
            result = prop.getValue();
            boolean status = result.equals(propertyValue);
            conn.setStatus(status);
            return status;
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error reading xwiki rest call result", e);
            conn.setStatus(false);
            return false;
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Error in xwiki connector", e);
        conn.setStatus(false);
        conn.setResponse("updateMetadata failed with exception: " + e.getMessage());
        return false;
    }
}

From source file:org.bonitasoft.connectors.xwiki.common.XWikiRestClient.java

/**
 * GET an XWiki MetaData using REST/* w  ww  .  j av  a 2  s  .  co  m*/
 * @throws IOException 
 * @throws HttpException 
 */
public String getMetadata(String wikiName, String spaceName, String pageName, String className,
        String propertyName, XWikiConnector conn) throws HttpException, IOException {
    try {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("getMetadata wikiName=" + wikiName + " spaceName=" + spaceName + " pageName=" + pageName
                    + " className=" + className + " propertyName=" + propertyName);
        }

        String uri = server + "/xwiki/rest/wikis/" + wikiName + "/spaces/" + spaceName + "/pages/" + pageName
                + "/objects/" + className + "/0/properties/" + propertyName;
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("GET " + uri);
        }

        HttpClient httpClient = new HttpClient();
        JAXBContext context = JAXBContext.newInstance("org.xwiki.rest.model.jaxb");
        Unmarshaller unmarshaller = context.createUnmarshaller();

        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        httpClient.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);

        GetMethod getMethod = new GetMethod(uri);
        getMethod.addRequestHeader("Accept", "application/xml");
        httpClient.executeMethod(getMethod);

        Object result = "";
        String returnString = getMethod.getResponseBodyAsString();
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("HTTP Result: " + returnString);
        }
        conn.setResponse(returnString);
        try {
            Property prop = (Property) unmarshaller.unmarshal(new StreamSource(new StringReader(returnString)));
            result = prop.getValue();
            conn.setStatus(true);
            if (result == null)
                return null;
            else
                return result.toString();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error reading xwiki rest call result", e);
            conn.setStatus(false);
            return null;
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Error in xwiki connector", e);
        conn.setStatus(false);
        conn.setResponse("getMetadata failed with exception: " + e.getMessage());
        return null;
    }
}

From source file:org.candlepin.client.CandlepinConnection.java

/**
 * Connects to another Candlepin instance located at the given uri.
 * @param clazz the client class to create.
 * @param creds authentication credentials for the given uri.
 * @param uri the Candlepin instance to connect to
 * @return Client proxy used to interact with Candlepin via REST API.
 *///ww  w  .ja v a  2s.c  o m
public <T> T connect(Class<T> clazz, Credentials creds, String uri) {
    HttpClient httpclient = new HttpClient();
    httpclient.getState().setCredentials(AuthScope.ANY, creds);
    ClientExecutor clientExecutor = new ApacheHttpClientExecutor(httpclient);
    return ProxyFactory.create(clazz, uri, clientExecutor);
}

From source file:org.candlepin.client.DefaultCandlepinClientFacade.java

protected CandlepinConsumerClient clientWithCredentials(String username, String password) {
    try {/*from w ww .  ja  v a2s.c o  m*/
        HttpClient httpclient = new HttpClient();
        httpclient.getParams().setAuthenticationPreemptive(true);
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        httpclient.getState().setCredentials(AuthScope.ANY, creds);
        CustomSSLProtocolSocketFactory factory = new CustomSSLProtocolSocketFactory(config, false);
        setHttpsProtocol(httpclient, factory);
        CandlepinConsumerClient client = ProxyFactory.create(CandlepinConsumerClient.class,
                config.getServerURL(), new ApacheHttpClientExecutor(httpclient));
        return client;
    } catch (Exception e) {
        throw new ClientException(e);
    }
}