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:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @param httpServletRequest Request object pertaining to the proxied HTTP request
 * @throws IOException      Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *///w  w  w .java2 s  .c  om
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    getCredential(httpServletRequest.getParameter("servername"));
    if (credentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    httpMethodProxyRequest.setFollowRedirects(true);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(stringLocation
                    .replace(getProxyHostAndPort(httpServletRequest) + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, response);
        } else {
            response = new String(ungzip(httpMethodProxyRequest.getResponseBody()));
        }
        httpServletResponse.setContentLength(response.length());
    }

    // Send the content to the client
    if (intProxyResponseCode == 200)
        httpServletResponse.getWriter().write(response);
    else
        httpServletResponse.getWriter().write(intProxyResponseCode);
}

From source file:com.googlecode.fascinator.common.BasicHttpClient.java

/**
 * Gets an HTTP client. If authentication is required, the authenticate()
 * method must be called prior to this method.
 * //w  w  w. j a v a 2 s.  c  o  m
 * @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);
        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:edu.internet2.middleware.shibboleth.common.config.metadata.HTTPMetadataProviderBeanDefinitionParser.java

/**
 * Sets the basic authentication properties, if any, for the HTTP client used to fetch metadata.
 * //from   w ww  .java  2  s.  c o  m
 * @param httpClient the HTTP client
 * @param config the metadata provider configuration
 * @param providerId the ID of the metadata provider
 * @param metadataURL the URL from which metadata will be fetched
 */
protected void setHttpBasicAuthSettings(HttpClient httpClient, Element config, String providerId,
        URL metadataURL) {
    String authUser = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthUser"));
    if (authUser == null) {
        return;
    }
    log.debug("Metadata provider '{}' HTTP Basic Auth username: {}", providerId, authUser);

    String authPassword = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthPassword"));
    log.debug("Metadata provider '{}' HTTP Basic Auth password not show", providerId);

    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authUser, authPassword);
    AuthScope authScope = new AuthScope(metadataURL.getHost(), metadataURL.getPort());
    httpClient.getState().setCredentials(authScope, credentials);
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

private void addWorkspace(String name) {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces";
    PostMethod post = new PostMethod(strURL);

    post.setRequestHeader("Content-type", "text/xml");
    post.setRequestEntity(// w  ww.  j a v a2 s  . c o m
            new StringRequestEntity("<?xml version=\"1.0\"?><workspace><name>" + name + "</name></workspace>"));
    post.setDoAuthentication(true);

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(post);

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        post.releaseConnection();
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

private void publishShapefile(String workspace, String datastore, String shp) {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/" + workspace + "/datastores/" + datastore
            + "/external.shp";
    PutMethod put = new PutMethod(strURL);

    put.setRequestHeader("Content-type", "text/plain");
    put.setRequestEntity(new StringRequestEntity(shp));
    put.setDoAuthentication(true);/*w ww .ja v a2s  . co m*/

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(put);

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        put.releaseConnection();
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

private void publishPostGISTable(String name) {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/crwgs84/datastores/public/featuretypes";
    PostMethod post = new PostMethod(strURL);

    post.setRequestHeader("Content-type", "text/xml");
    post.setRequestEntity(new StringRequestEntity(
            "<?xml version=\"1.0\"?><featureType><name>" + name + "</name></featureType>"));
    post.setDoAuthentication(true);//from  www. ja v a 2 s .c o m

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(post);

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        post.releaseConnection();
    }

}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String testREST_GET_WorkSpace() {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/acme";
    GetMethod get = new GetMethod(strURL);

    get.setRequestHeader("Accept", "text/xml");
    get.setDoAuthentication(true);//from  w  ww.j  a  va 2  s . c  o  m

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(get);

        System.out.println("Response: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //System.out.println(post.getResponseBodyAsStream());

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        get.releaseConnection();
    }

    return "testREST_GET_WorkSpace";
}

From source file:com.datos.vfs.provider.http.HttpClientFactory.java

/**
 * Creates a new connection to the server.
 * @param builder The HttpFileSystemConfigBuilder.
 * @param scheme The protocol.//from w w  w . j  ava 2s  . c  o m
 * @param hostname The hostname.
 * @param port The port number.
 * @param username The username.
 * @param password The password
 * @param fileSystemOptions The file system options.
 * @return a new HttpClient connection.
 * @throws FileSystemException if an error occurs.
 * @since 2.0
 */
public static HttpClient createConnection(final HttpFileSystemConfigBuilder builder, final String scheme,
        final String hostname, final int port, final String username, final String password,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    HttpClient client;
    try {
        final HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        final HttpConnectionManagerParams connectionMgrParams = mgr.getParams();

        client = new HttpClient(mgr);

        final HostConfiguration config = new HostConfiguration();
        config.setHost(hostname, port, scheme);

        if (fileSystemOptions != null) {
            final String proxyHost = builder.getProxyHost(fileSystemOptions);
            final int proxyPort = builder.getProxyPort(fileSystemOptions);

            if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
                config.setProxy(proxyHost, proxyPort);
            }

            final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
            if (proxyAuth != null) {
                final UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
                        new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME,
                                UserAuthenticationData.PASSWORD });

                if (authData != null) {
                    final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.USERNAME, null)),
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.PASSWORD, null)));

                    final AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
                    client.getState().setProxyCredentials(scope, proxyCreds);
                }

                if (builder.isPreemptiveAuth(fileSystemOptions)) {
                    final HttpClientParams httpClientParams = new HttpClientParams();
                    httpClientParams.setAuthenticationPreemptive(true);
                    client.setParams(httpClientParams);
                }
            }

            final Cookie[] cookies = builder.getCookies(fileSystemOptions);
            if (cookies != null) {
                client.getState().addCookies(cookies);
            }
        }
        /**
         * ConnectionManager set methods must be called after the host & port and proxy host & port
         * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
         * tries to locate the host configuration.
         */
        connectionMgrParams.setMaxConnectionsPerHost(config,
                builder.getMaxConnectionsPerHost(fileSystemOptions));
        connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));

        connectionMgrParams.setConnectionTimeout(builder.getConnectionTimeout(fileSystemOptions));
        connectionMgrParams.setSoTimeout(builder.getSoTimeout(fileSystemOptions));

        client.setHostConfiguration(config);

        if (username != null) {
            final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            final AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
            client.getState().setCredentials(scope, creds);
        }
    } catch (final Exception exc) {
        throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
    }

    return client;
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String testREST_PUT() {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/acme/datastores/reky/file.shp";
    PutMethod put = new PutMethod(strURL);

    put.setRequestHeader("Content-type", "application/zip");
    put.setRequestEntity(new FileRequestEntity(new File("reky.zip"), "application/zip"));
    put.setDoAuthentication(true);/*w w  w.  j a v  a 2 s.c  om*/

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(put);

        System.out.println("Response: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(put.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //System.out.println(post.getResponseBodyAsStream());

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        put.releaseConnection();
    }

    return "TestREST2";
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String testREST_PUT_Local() {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/acme/datastores/zeleznice/external.shp";
    PutMethod put = new PutMethod(strURL);

    put.setRequestHeader("Content-type", "text/plain");
    put.setRequestEntity(new StringRequestEntity("file:///data/shpdata/cr-shp-wgs84/linie/zeleznice.shp"));
    put.setDoAuthentication(true);//  w  ww  .ja  v  a  2s  .co  m

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(put);

        System.out.println("Response: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(put.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //System.out.println(post.getResponseBodyAsStream());

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        put.releaseConnection();
    }

    return "http://localhost:8080/geoserver/acme/wms?service=WMS&version=1.3.0&request=GetCapabilities";
}