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

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

Introduction

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

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:org.jahia.services.notification.HttpClientServiceTest.java

@Test
public void testNoProxySettingsDefined() throws HttpException {
    initClient();//from   w w w . ja  va2 s .  c  o m
    HttpClient httpClient = httpClientService.getHttpClient(null);
    assertNull(httpClient.getState().getProxyCredentials(AuthScope.ANY));
    assertNull(httpClient.getHostConfiguration().getProxyHost());

    assertTrue(httpClient == httpClientService.getHttpClient("http://www.jahia.com"));
    assertTrue(httpClient == httpClientService.getHttpClient("https://www.jahia.com"));
    assertTrue(httpClient == httpClientService.getHttpClient("http://localhost:8080"));
    assertTrue(httpClient == httpClientService.getHttpClient("https://localhost:8080"));
    assertTrue(httpClient == httpClientService.getHttpClient("www.jahia.com:9090"));
    assertTrue(httpClient == httpClientService.getHttpClient("localhost:9090"));
    assertTrue(httpClient == httpClientService.getHttpClient("/aaa.html"));
}

From source file:org.jahia.test.services.feedimporter.GetFeedActionTest.java

private void testFeed(String nodeName, String feedURL, String testNodeName)
        throws RepositoryException, IOException, JSONException {
    JCRSessionWrapper baseSession = JCRSessionFactory.getInstance().getCurrentUserSession();
    JCRSiteNode site = (JCRSiteNode) baseSession.getNode(SITECONTENT_ROOT_NODE);

    JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession(Constants.EDIT_WORKSPACE,
            LanguageCodeConverters.languageCodeToLocale(site.getDefaultLanguage()));
    JCRNodeWrapper node = session.getNode("/sites/" + TESTSITE_NAME + "/contents/feeds");

    session.checkout(node);/*www .j ava  2s  .c o  m*/

    JCRNodeWrapper sdaFeedNode = node.addNode(nodeName, "jnt:feed");

    sdaFeedNode.setProperty("url", feedURL);

    session.save();
    JCRPublicationService.getInstance().publishByMainId(sdaFeedNode.getIdentifier(), Constants.EDIT_WORKSPACE,
            Constants.LIVE_WORKSPACE, null, true, null);

    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);

    String baseurl = getBaseServerURL() + Jahia.getContextPath() + "/cms";
    final URL url = new URL(baseurl + "/render/default/en" + sdaFeedNode.getPath() + ".getfeed.do");

    Credentials defaultcreds = new UsernamePasswordCredentials("root", "root1234");
    client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
            defaultcreds);

    client.getHostConfiguration().setHost(url.getHost(), url.getPort(), url.getProtocol());

    PostMethod getFeedAction = new PostMethod(url.toExternalForm());
    try {
        getFeedAction.addRequestHeader(new Header("accept", "application/json"));

        client.executeMethod(getFeedAction);
        assertEquals("Bad result code", 200, getFeedAction.getStatusCode());

        JSONObject response = new JSONObject(getFeedAction.getResponseBodyAsString());
    } finally {
        getFeedAction.releaseConnection();
    }

    JCRSessionWrapper liveSession = JCRSessionFactory.getInstance().getCurrentUserSession(
            Constants.LIVE_WORKSPACE, LanguageCodeConverters.languageCodeToLocale(site.getDefaultLanguage()));
    JCRNodeWrapper target = liveSession
            .getNode("/sites/" + TESTSITE_NAME + "/contents/feeds/" + nodeName + "/" + testNodeName);
    // assertNotNull("Feed should have some childs", target); deactivated because we load content in a single language.
}

From source file:org.jahia.test.services.render.filter.cache.base.CacheFilterHttpTest.java

public GetMethod executeCall(URL url, String user, String password, String requestId) throws IOException {
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);

    if (user != null && password != null) {
        Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
        client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                defaultcreds);// w  w w .  j av a 2  s .c om
    }

    client.getHostConfiguration().setHost(url.getHost(), url.getPort(), url.getProtocol());

    GetMethod method = new GetMethod(url.toExternalForm());
    if (requestId != null) {
        method.setRequestHeader("request-id", requestId);
    }
    client.executeMethod(method);
    return method;
}

From source file:org.jasig.portal.services.HttpClientFactoryBean.java

@Override
protected HttpClient createInstance() throws Exception {
    final HttpClient httpClient;
    if (this.httpConnectionManager != null) {
        httpClient = new HttpClient(this.httpConnectionManager);
    } else {//from w w  w . j a va2  s .  c  o m
        httpClient = new HttpClient();
    }

    if (this.proxyHost != null) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    return httpClient;
}

From source file:org.jasig.portal.services.HttpClientManager.java

public static HttpClient getNewHTTPClient() {
    if (PROXY_HOST == null) {
        return new HttpClient(connectionManager);
    } else {// w w  w .ja v  a 2 s. c om
        HttpClient result = new HttpClient(connectionManager);
        result.getHostConfiguration().setProxy(PROXY_HOST, PROXY_PORT);
        return result;
    }
}

From source file:org.jboss.tools.common.util.HttpUtil.java

private static HttpClient createHttpClient(String url, IProxyService proxyService) throws IOException {
    HttpClient httpClient = new HttpClient();

    if (proxyService.isProxiesEnabled()) {
        IProxyData[] proxyData = proxyService.getProxyData();
        URL netUrl = new URL(url);
        String hostName = netUrl.getHost();
        String[] nonProxiedHosts = proxyService.getNonProxiedHosts();
        boolean nonProxiedHost = false;
        for (int i = 0; i < nonProxiedHosts.length; i++) {
            String nonProxiedHostName = nonProxiedHosts[i];
            if (nonProxiedHostName.equalsIgnoreCase(hostName)) {
                nonProxiedHost = true;/*from w w  w. j av a  2  s  .  c  o m*/
                break;
            }
        }
        if (!nonProxiedHost) {
            for (int i = 0; i < proxyData.length; i++) {
                IProxyData proxy = proxyData[i];
                if (IProxyData.HTTP_PROXY_TYPE.equals(proxy.getType())) {
                    String proxyHostName = proxy.getHost();
                    if (proxyHostName == null) {
                        break;
                    }
                    int portNumber = proxy.getPort();
                    if (portNumber == -1) {
                        portNumber = 80;
                    }
                    httpClient.getHostConfiguration().setProxy(proxyHostName, portNumber);
                    if (proxy.isRequiresAuthentication()) {
                        String userName = proxy.getUserId();
                        if (userName != null) {
                            String password = proxy.getPassword();
                            httpClient.getState().setProxyCredentials(
                                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                                    new UsernamePasswordCredentials(userName, password));
                        }
                    }
                    break; // Use HTTP proxy only.
                }
            }
        }
    }

    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

    return httpClient;
}

From source file:org.jetbrains.plugins.github.api.GithubApiUtil.java

@NotNull
private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth, boolean useProxy) {
    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)/*from ww w. jav  a  2s. c om*/

    client.getParams().setContentCharset("UTF-8");
    // Configure proxySettings if it is required
    final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    if (useProxy && 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.getProxyLogin(), proxySettings.getPlainProxyPassword()));
        }
    }
    if (basicAuth != null) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword()));
    }
    return client;
}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

private static void setProxy(HttpClient httpClient) {
    final HTTPProxyInfo proxy = HTTPProxyInfo.getCurrent();
    if (proxy.host != null) {
        httpClient.getHostConfiguration().setProxy(proxy.host, proxy.port);
        if (proxy.user != null) {
            Pair<String, String> domainAndUser = getDomainAndUser(proxy.user);
            UsernamePasswordCredentials creds = new NTCredentials(domainAndUser.second, proxy.password,
                    proxy.host, domainAndUser.first);
            httpClient.getState().setProxyCredentials(AuthScope.ANY, creds);
        }//w ww.  j  a  v a 2s  . c  o m
    } else {
        httpClient.getHostConfiguration().setProxyHost(null);
    }
}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

private static void setCredentials(final @NotNull HttpClient httpClient, final @NotNull Credentials credentials,
        final @NotNull URI serverUri) {
    if (credentials.getType() == Credentials.Type.Alternate) {
        HostParams parameters = httpClient.getHostConfiguration().getParams();
        Collection<Header> headers = (Collection<Header>) parameters.getParameter(HostParams.DEFAULT_HEADERS);

        if (headers == null) {
            headers = new ArrayList<Header>();
            parameters.setParameter(HostParams.DEFAULT_HEADERS, headers);
        }/*from w  ww .  ja  va  2s  .co  m*/

        Header authHeader = ContainerUtil.find(headers, new Condition<Header>() {
            @Override
            public boolean value(Header header) {
                return header.getName().equals(HTTPConstants.HEADER_AUTHORIZATION);
            }
        });

        if (authHeader == null) {
            authHeader = new Header(HTTPConstants.HEADER_AUTHORIZATION, "");
            headers.add(authHeader);
        }

        authHeader.setValue(BasicScheme.authenticate(
                new UsernamePasswordCredentials(credentials.getUserName(), credentials.getPassword()),
                "UTF-8"));
    } else {
        final NTCredentials ntCreds = new NTCredentials(credentials.getUserName(), credentials.getPassword(),
                serverUri.getHost(), credentials.getDomain());
        httpClient.getState().setCredentials(AuthScope.ANY, ntCreds);
        httpClient.getParams().setBooleanParameter(USE_NATIVE_CREDENTIALS,
                credentials.getType() == Credentials.Type.NtlmNative);
    }
}

From source file:org.jivesoftware.community.http.impl.HttpClientManagerImpl.java

public HttpClient getClient(URL url,
        com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.CredentialSupplier credentialSupplier,
        int timeout) {
    HttpClient client = new HttpClient();
    HttpConnectionManager conManager = client.getHttpConnectionManager();

    if (JiveGlobals.getProperty("http.proxyHost") != null
            && JiveGlobals.getProperty("http.proxyPort") != null) {
        client.getHostConfiguration().setProxy(JiveGlobals.getProperty("http.proxyHost"),
                Integer.parseInt(JiveGlobals.getProperty("http.proxyPort")));
        if (JiveGlobals.getProperty("http.proxyUsername") != null
                && JiveGlobals.getProperty("http.proxyPassword") != null) {
            HttpState state = new HttpState();
            state.setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(JiveGlobals.getProperty("http.proxyUserName"),
                            JiveGlobals.getProperty("http.proxyPassword")));
            client.setState(state);//from   w w  w.j a v  a  2  s . co m
        }
    }
    if (timeout > 0) {
        conManager.getParams().setParameter("http.connection.timeout", Integer.valueOf(timeout));
        conManager.getParams().setParameter("http.socket.timeout", Integer.valueOf(timeout));
    }
    if (isHTTPS(url)) {
        int port = url.getPort() <= -1 ? 443 : url.getPort();
        Protocol myhttps = new Protocol("https", new DummySSLSocketFactory(), port);
        Protocol.registerProtocol("https", myhttps);
        client.getHostConfiguration().setHost(url.getHost(), port, myhttps);
    } else {
        int port = url.getPort() <= -1 ? 80 : url.getPort();
        client.getHostConfiguration().setHost(url.getHost(), port);
    }
    if (url.getUserInfo() != null && credentialSupplier == null)
        credentialSupplier = new BasicAuthCredentials(url.getUserInfo());

    if (credentialSupplier != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(new AuthScope(url.getHost(), -1, AuthScope.ANY_REALM),
                credentialSupplier.getCredentials(null, url.getHost()));
    }
    return client;
}