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.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);//from ww  w.j  av  a  2 s. 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);//from w ww.j ava 2  s.co m
    }

    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.portlet.calendar.adapter.ConfigurableHttpCalendarAdapter.java

/**
 * Uses Commons HttpClient to retrieve the specified url (optionally with the provided 
 * {@link Credentials}.//w  w  w  .j a  v a  2 s .  co  m
 * The response body is returned as an {@link InputStream}.
 * 
 * @param url URL of the calendar to be retrieved
 * @param credentials {@link Credentials} to use with the request, if necessary (null is ok if credentials not required)
 * @return the body of the http response as a stream
 * @throws CalendarException wraps all potential {@link Exception} types 
 */
protected InputStream retrieveCalendarHttp(String url, Credentials credentials) throws CalendarException {
    HttpClient client = new HttpClient();
    if (null != credentials) {
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }
    GetMethod get = null;

    try {

        if (log.isDebugEnabled()) {
            log.debug("Retrieving calendar " + url);
        }
        get = new GetMethod(url);
        int rc = client.executeMethod(get);
        if (rc == HttpStatus.SC_OK) {
            // return the response body
            log.debug("request completed successfully");
            InputStream in = get.getResponseBodyAsStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            IOUtils.copyLarge(in, buffer);
            return new ByteArrayInputStream(buffer.toByteArray());
        } else {
            log.warn("HttpStatus for " + url + ":" + rc);
            throw new CalendarException(
                    "non successful status code retrieving " + url + ", status code: " + rc);
        }
    } catch (HttpException e) {
        log.warn("Error fetching iCalendar feed", e);
        throw new CalendarException("Error fetching iCalendar feed", e);
    } catch (IOException e) {
        log.warn("Error fetching iCalendar feed", e);
        throw new CalendarException("Error fetching iCalendar feed", e);
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

}

From source file:org.jasig.portlet.calendar.adapter.exchange.ExchangeHttpWebServiceMessageSender.java

/**
 * Return an HttpClient instance configured with authentication credentials
 * for the current user.  This implementation caches HttpClient instances
 * in a RequestContextHolder for later use by the same user.
 * /*from  w  w  w  . j  a v a2  s.  c o  m*/
 * @return HttpClient authenticated client
 */
protected HttpClient getClient() {
    // attempt to find a cached HttpClient instance in the ThreadLocal
    final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    HttpClient client = (HttpClient) requestAttributes.getAttribute(EXCHANGE_CLIENT_ATTRIBUTE,
            RequestAttributes.SCOPE_SESSION);

    // if no client was found, create a new one using the cached credentials
    if (client == null) {
        client = new HttpClient(connectionManager);

        // configure basic authentication using the current user's credentials
        Credentials credentials = getCredentials();
        client.getState().setCredentials(AuthScope.ANY, credentials);
        client.getParams().setAuthenticationPreemptive(true);

        // save the HttpClient in a ThreadLocal
        requestAttributes.setAttribute(EXCHANGE_CLIENT_ATTRIBUTE, client, RequestAttributes.SCOPE_SESSION);
    }

    return client;
}

From source file:org.jasig.portlet.calendar.adapter.exchange.ExchangeHttpWebServiceMessageSenderTest.java

@Test
public void testGetClient() {
    HttpClient client = sender.getClient();
    assertNotNull(client);/*from  www  . j  a va2s.  co  m*/
    assertEquals(1000, client.getHttpConnectionManager().getParams().getConnectionTimeout());
    assertEquals(1000, client.getHttpConnectionManager().getParams().getSoTimeout());
    assertEquals(5, client.getHttpConnectionManager().getParams().getMaxTotalConnections());
    assertEquals(5, client.getHttpConnectionManager().getParams().getDefaultMaxConnectionsPerHost());

    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) client.getState()
            .getCredentials(AuthScope.ANY);
    assertEquals("user", credentials.getUserName());
    assertEquals("pass", credentials.getPassword());
}

From source file:org.jboss.ejb3.test.clusteredservice.unit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//from   ww  w .j a va  2s  . c  om
        log.debug("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        log.debug("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        log.debug("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        log.debug(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.jboss.fuse.examples.cxf.jaxrs.security.client.Client.java

public static void main(String args[]) throws Exception {
    // Now we need to use the basic authentication to send the request
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
    // Use basic authentication
    AuthScheme scheme = new BasicScheme();

    /**// www. ja  va2 s. c  o m
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/customers/123
     * returns the XML document representing customer 123
     *
     * On the server side, it matches the CustomerService's getCustomer() method
     */
    System.out.println("Sent HTTP GET request to query customer info with basic authentication info.");
    GetMethod get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/customers/123");
    get.getHostAuthState().setAuthScheme(scheme);
    try {
        httpClient.executeMethod(get);
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/customers/123
     * without passing along authentication credentials - this will result in a security exception in the response.
     */
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query customer info without basic authentication info.");
    get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/customers/123");
    try {
        httpClient.executeMethod(get);
        // we should get the security exception here
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/orders/223/products/323
     * returns the XML document representing product 323 in order 223
     *
     * On the server side, it matches the Order's getProduct() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/orders/223/products/323");
    get.getHostAuthState().setAuthScheme(scheme);
    try {
        httpClient.executeMethod(get);
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP PUT http://localhost:8181/cxf/securecrm/customerservice/customers is used to upload the contents of
     * the update_customer.xml file to update the customer information for customer 123.
     *
     * On the server side, it matches the CustomerService's updateCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");

    String inputFile = Client.class.getResource("update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod("http://localhost:8181/cxf/securecrm/customerservice/customers");
    put.getHostAuthState().setAuthScheme(scheme);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);

    try {
        int result = httpClient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    /**
     * HTTP POST http://localhost:8181/cxf/securecrm/customerservice/customers is used to upload the contents of
     * the add_customer.xml file to add a new customer to the system.
     *
     * On the server side, it matches the CustomerService's addCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = Client.class.getResource("add_customer.xml").getFile();
    input = new File(inputFile);
    PostMethod post = new PostMethod("http://localhost:8181/cxf/securecrm/customerservice/customers");
    post.getHostAuthState().setAuthScheme(scheme);
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);

    try {
        int result = httpClient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:org.jboss.test.cluster.classloader.leak.test.ClassloaderLeakTestBase.java

private void setCookieDomainToThisServer(HttpClient client, String server) {
    // Get the session cookie
    Cookie sessionID = getSessionCookie(client, server);
    // Reset the domain so that the cookie will be sent to server1
    sessionID.setDomain(server);//  w w w .  j  a v a2  s  .c o m
    client.getState().addCookie(sessionID);
}

From source file:org.jboss.test.cluster.classloader.leak.test.ClassloaderLeakTestBase.java

protected Cookie getSessionCookie(HttpClient client, String server) {
    // Get the state for the JSESSIONID
    HttpState state = client.getState();
    // Get the JSESSIONID so we can reset the host
    Cookie[] cookies = state.getCookies();
    Cookie sessionID = null;/*  w  w  w  .j a  v  a 2s  .c o m*/
    for (int c = 0; c < cookies.length; c++) {
        Cookie k = cookies[c];
        if (k.getName().equalsIgnoreCase("JSESSIONID"))
            sessionID = k;
    }
    if (sessionID == null) {
        fail("setCookieDomainToThisServer(): fail to find session id. Server name: " + server);
    }
    log.info("Saw JSESSIONID=" + sessionID);
    return sessionID;
}

From source file:org.jboss.test.cluster.defaultcfg.web.test.CrossContextCallsTestCase.java

/**
 * Makes a http call to the jsp that retrieves the attribute stored on the
 * session. When the attribute values mathes with the one retrieved earlier,
 * we have HttpSessionReplication.//ww  w.  j a v  a 2 s .  c o m
 * Makes use of commons-httpclient library of Apache
 *
 * @param client
 * @param url
 * @return session attribute
 */
protected String makeGetWithState(HttpClient client, String url) throws IOException {
    getLog().debug("makeGetWithState(): trying to get from url " + url);
    GetMethod method = new GetMethod(url);
    int responseCode = 0;
    try {
        HttpState state = client.getState();
        responseCode = client.executeMethod(method.getHostConfiguration(), method, state);
    } catch (IOException e) {
        e.printStackTrace();
        fail("HttpClient executeMethod fails." + e.toString());
    }
    assertTrue("Get OK with url: " + url + " responseCode: " + responseCode,
            responseCode == HttpURLConnection.HTTP_OK);

    String response = extractResponse(method);

    // Release the connection.
    // method.releaseConnection();

    return response;
}