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.jahia.ajax.gwt.helper.PublicationHelper.java

public void validateConnection(Map<String, String> props, JCRSessionWrapper jcrSession, Locale uiLocale)
        throws GWTJahiaServiceException {
    PostMethod post = null;//from  w w w.j  a v a2  s.c  om
    URL url = null;
    try {
        String languageCode = jcrSession.getNodeByIdentifier(props.get("node")).getResolveSite()
                .getDefaultLanguage();
        String theUrl = props.get("remoteUrl") + Render.getRenderServletPath() + "/live/" + languageCode
                + props.get("remotePath") + ".preparereplay.do";
        url = new URL(theUrl);
        post = new PostMethod(theUrl);
        post.addParameter("testOnly", "true");
        post.addRequestHeader("accept", "application/json");
        HttpState state = new HttpState();
        state.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(props.get("remoteUser"), props.get("remotePassword")));
        HttpClient httpClient = httpClientService.getHttpClient(theUrl);
        Credentials proxyCredentials = httpClient.getState().getProxyCredentials(AuthScope.ANY);
        if (proxyCredentials != null) {
            state.setProxyCredentials(AuthScope.ANY, proxyCredentials);
        }
        if (httpClient.executeMethod(null, post, state) != 200) {
            logger.warn("Connection to URL: {} failed with status {}", url, post.getStatusLine());
            throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                    "label.gwt.error.connection.failed.with.the.status", uiLocale, post.getStatusLine()));
        }
    } catch (RepositoryException e) {
        logger.error("Unable to get source node with identifier: " + props.get("node") + ". Cause: "
                + e.getMessage(), e);
        throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                "label.gwt.error.connection.failed.with.the.an.error", uiLocale, e.getMessage()));
    } catch (HttpException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
        throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                "label.gwt.error.connection.failed.with.the.an.error", uiLocale, e.getMessage()));
    } catch (IOException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
        throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                "label.gwt.error.connection.failed.with.the.an.error", uiLocale, e.getMessage()));
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.jahia.services.content.CrawlingPageVisitorTest.java

@Test
public void testPrecompileJsps() throws IOException {
    try {/*  w ww .  jav a 2  s .  com*/
        HttpClient client = new HttpClient();

        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jahia", "password"));

        GetMethod get = new GetMethod(getPrecompileServletURL() + "?compile_type=all&jsp_precompile=true");
        try {
            get.setDoAuthentication(true);

            int statusCode = client.executeMethod(get);

            assertEquals("Precompile servlet failed", HttpStatus.SC_OK, statusCode);
            assertThat("Precompilation found buggy JSPs", get.getResponseBodyAsString(),
                    containsString("No problems found!"));
            assertEquals("There were exceptions during the precompile process", "", appender.getErrorLogs());
        } finally {
            get.releaseConnection();
        }
    } catch (Exception e) {
        assertNotNull("Precompile servlet request threw exception: " + e.getLocalizedMessage(), null);
    }
}

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

private void testFeed(String nodeName, String feedURL, String testNodeName)
        throws RepositoryException, IOException, JSONException {

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

    session.checkout(node);//from w  w  w .ja  v a 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 = "http://localhost:8080" + 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());
    getFeedAction.addRequestHeader(new Header("accept", "application/json"));

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

    JSONObject response = new JSONObject(getFeedAction.getResponseBodyAsString());
    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.services.notification.HttpClientService.java

private static HttpClient cloneHttpClient(HttpClient source) {
    HttpClient cloned = new HttpClient(source.getParams(), source.getHttpConnectionManager());
    String sourceProxyHost = source.getHostConfiguration().getProxyHost();
    if (sourceProxyHost != null) {
        cloned.getHostConfiguration().setProxy(sourceProxyHost, source.getHostConfiguration().getProxyPort());
    }/* w ww . j a v  a2 s.c o m*/
    Credentials proxyCredentials = source.getState().getProxyCredentials(AuthScope.ANY);
    if (proxyCredentials != null) {
        HttpState state = new HttpState();
        state.setProxyCredentials(AuthScope.ANY, proxyCredentials);
        cloned.setState(state);
    }

    return cloned;

}

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

private static String initHttpClient(HttpClient client, String protocol) {
    String host = System.getProperty(protocol + ".proxyHost");
    int port = Integer.getInteger(protocol + ".proxyPort", -1).intValue();
    port = port != -1 ? port : Protocol.getProtocol(protocol).getDefaultPort();

    client.getHostConfiguration().setProxy(host, port);

    String key = host + ':' + port;

    Credentials credentials = null;//from   w ww.ja va 2s  .  c  o m
    String user = System.getProperty(protocol + ".proxyUser");
    if (StringUtils.isNotEmpty(user)) {
        credentials = new UsernamePasswordCredentials(user, System.getProperty(protocol + ".proxyPassword"));
        client.getState().setProxyCredentials(AuthScope.ANY, credentials);
    }

    logger.info("Initialized HttpClient for {} protocol using proxy {} {} credentials",
            new String[] { protocol.toUpperCase(), key, credentials != null ? "with" : "without" });

    return key;
}

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

private void ensureProxy(String url, String expectedHost, int expectedPort, String user, String pwd) {
    HttpClient httpClient = httpClientService.getHttpClient(url);
    assertEquals(expectedHost, httpClient.getHostConfiguration().getProxyHost());
    assertEquals(expectedPort, httpClient.getHostConfiguration().getProxyPort());

    Credentials credentials = httpClient.getState().getProxyCredentials(AuthScope.ANY);
    if (null == user) {
        assertNull(credentials);/*  w  w w. j a va2s  .  c o m*/
    } else {
        assertNotNull(credentials);
        assertTrue(credentials instanceof UsernamePasswordCredentials);
        assertEquals(user, ((UsernamePasswordCredentials) credentials).getUserName());
        assertEquals(pwd, ((UsernamePasswordCredentials) credentials).getPassword());
    }
}

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

private void testHttpProxyDefined(int definedPort, int expectedPort) throws HttpException {
    System.setProperty("http.proxyHost", "httpProxy");
    if (definedPort > 0) {
        System.setProperty("http.proxyPort", String.valueOf(definedPort));
    }/*from  w w w  .  j  a va2 s .  c  om*/

    initClient();
    HttpClient httpClient = httpClientService.getHttpClient(null);
    assertNull(httpClient.getState().getProxyCredentials(AuthScope.ANY));

    ensureProxy(null, "httpProxy", expectedPort);

    ensureProxy("http://www.jahia.com", "httpProxy", expectedPort);
    ensureProxy("http://localhost:8080", "httpProxy", expectedPort);
    ensureProxy("www.jahia.com:9090", "httpProxy", expectedPort);
    ensureProxy("localhost:9090", "httpProxy", expectedPort);
    ensureProxy("http://localhost:8080", "httpProxy", expectedPort);

    ensureProxy("https://www.jahia.com", null, -1);
    ensureProxy("https://localhost:8080", null, -1);

    ensureProxy("/aaa.html", null, -1);
}

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

private void testHttpsProxyDefined(int definedPort, int expectedPort) throws HttpException {
    System.setProperty("https.proxyHost", "httpsProxy");
    if (definedPort > 0) {
        System.setProperty("https.proxyPort", String.valueOf(definedPort));
    }/* w w w . j av a2s.c  om*/

    initClient();
    HttpClient httpClient = httpClientService.getHttpClient(null);
    assertNull(httpClient.getState().getProxyCredentials(AuthScope.ANY));

    ensureProxy(null, "httpsProxy", expectedPort);

    ensureProxy("http://www.jahia.com", null, -1);
    ensureProxy("http://localhost:8080", null, -1);
    ensureProxy("www.jahia.com:9090", null, -1);
    ensureProxy("localhost:9090", null, -1);
    ensureProxy("http://localhost:8080", null, -1);

    ensureProxy("https://www.jahia.com", "httpsProxy", expectedPort);
    ensureProxy("https://localhost:8080", "httpsProxy", expectedPort);

    ensureProxy("/aaa.html", null, -1);
}

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

@Test
public void testNoProxySettingsDefined() throws HttpException {
    initClient();/*  ww  w  .j ava 2 s  .com*/
    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.content.CrawlingPageVisitorTest.java

@Test
public void testPrecompileJsps() throws IOException {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jahia", "password"));
    String url = getPrecompileServletURL() + "?compile_type=all&jsp_precompile=true";
    logger.info("Starting the precompileServlet with the following url: " + url);
    GetMethod get = new GetMethod(url);
    try {//from  w w  w .j a va  2 s .  c o  m
        get.setDoAuthentication(true);
        int statusCode = client.executeMethod(get);
        Assert.assertEquals("Precompile servlet failed", HttpStatus.SC_OK, statusCode);
        Assert.assertThat("Precompilation found buggy JSPs", get.getResponseBodyAsString(),
                containsString("No problems found!"));
        Assert.assertEquals("There were errors during the precompile process", "",
                toText(logEventCollector.getCollectedEvents()));
    } finally {
        get.releaseConnection();
    }
}