Example usage for org.apache.commons.httpclient HttpMethod releaseConnection

List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod releaseConnection.

Prototype

public abstract void releaseConnection();

Source Link

Usage

From source file:org.jasig.portal.security.provider.SamlAssertionFilter.java

public void doHttpFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("HTTP headers: [" + headersAsString(req) + "]");
    }/*from   ww w  .  j ava  2  s. com*/

    final int assertionCount = this.getAssertionCount(req);

    String idp = null, assertion = null, signingKeys = null;

    if (assertionCount > 0) {
        idp = req.getHeader("Shib-Identity-Provider");
        final String firstAssertionHeader = req.getHeader("Shib-Assertion-01");

        if (idpPublicKeysSessionAttributeName != null) {
            signingKeys = req.getHeader("Meta-Signing-Keys");
        }

        if (StringUtils.isNotEmpty(firstAssertionHeader)) {
            if (logger.isInfoEnabled()) {
                logger.info("Retrieving SAML assertion from the URL: " + firstAssertionHeader);
            }
            final HttpMethod method = new GetMethod(firstAssertionHeader);

            try {
                int result = this.httpClient.executeMethod(method);

                if (result >= HttpStatus.SC_OK && result < 300) {
                    assertion = method.getResponseBodyAsString();
                } else {
                    logger.error("Unsupported HTTP result code when retrieving the SAML assertion: " + result);
                }
            } catch (Exception ex) {
                // There is nothing that can be done about this exception other than to log it
                // Exception must be caught and not rethrown to allow normal processing to continue
                logger.error("Exception caught when trying to retrieve SAML assertion.", ex);
            } finally {
                method.releaseConnection();
            }
        } else {
            logger.error("SAML assertion URL not present, but the assertion count was " + assertionCount + ".");
        }
    } else {
        logger.warn("SAML assertion count not present or zero");
    }

    // Start with processing the login.  This way if the login process creates a new session,
    // the assertion will remain in the session to be picked up by SamlAssertionUserInfoService
    try {
        chain.doFilter(req, res);
    } finally {
        HttpSession session = req.getSession();

        if (assertion != null) {
            session.setAttribute(samlAssertionSessionAttributeName, assertion);
        }
        if (idp != null) {
            session.setAttribute("IdP", idp);
        }
        if (signingKeys != null) {
            session.setAttribute(idpPublicKeysSessionAttributeName, signingKeys);
        }
    }
}

From source file:org.jasig.portlet.weather.dao.worldwide.WorldWeatherOnlineDaoImpl.java

public Collection<Location> find(String location) {
    final String url = FIND_URL.replace("@KEY@", key).replace("@QUERY@",
            QuietUrlCodec.encode(location, Constants.URL_ENCODING));

    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {//  ww  w . j a  v a2 s .  com
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();

        List<Location> locations = deserializeSearchResults(inputStream);

        return locations;

    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } catch (JAXBException e) {
        throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jasig.portlet.weather.dao.worldwide.WorldWeatherOnlineDaoImpl.java

protected Object getAndDeserialize(String url, TemperatureUnit unit) {
    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {//from  w  ww.  j  a  v a 2s .  co m
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();

        Weather weather = deserializeWeatherResult(inputStream, unit);

        return weather;

    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } catch (JAXBException e) {
        throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e);
    } catch (ParseException e) {
        throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jasig.portlet.weather.dao.yahoo.YahooWeatherDaoImpl.java

public Collection<Location> find(String location) {
    if ((key == null) || (key.length() == 0)) {
        MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(
                new String[] { ERR_API_MISSING_KEY, ERR_GENERAL_KEY });
        throw new InvalidConfigurationException(messageSource.getMessage(resolvable, Locale.getDefault()));
    }/*from w w w.  ja  va  2 s  . co  m*/

    final String url = FIND_URL.replace("@KEY@", key).replace("@QUERY@",
            QuietUrlCodec.encode(location, Constants.URL_ENCODING));

    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();

        List<Location> locations = locationParsingService.parseLocations(inputStream);

        return locations;

    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jasig.portlet.weather.dao.yahoo.YahooWeatherDaoImpl.java

protected Object getAndDeserialize(String url) {
    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {/*from  w  w  w .j a va2  s.  co  m*/
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();
        return weatherParsingService.parseWeather(inputStream);
    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jboss.test.cluster.apache_tomcat.HttpSessionReplicationTestCase.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.//from ww  w  .j  ava  2s  .  co  m
 * Makes use of commons-httpclient library of Apache
 *
 * @param client
 * @param method
 * @return session attribute
 */
private String makeGet(HttpClient client, HttpMethod method) {
    try {
        client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log.debug("A recoverable exception occurred, retrying." + e.getMessage());
    } catch (IOException e) {
        log.debug(e);
        e.printStackTrace();
        System.exit(-1);
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

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

    // Deal with the response.
    // Use caution: ensure correct character encoding and is not binary data
    return new String(responseBody);
}

From source file:org.jboss.test.cluster.httpsessionreplication.HttpSessionReplicationUnitTestCase.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.//  w ww  . ja v  a2  s.  c o  m
 * Makes use of commons-httpclient library of Apache
* @param client
* @param method
* @return session attribute
* @throws IOException
*/
private String makeGet(HttpClient client, HttpMethod method) throws IOException {
    //       Execute the method.
    int statusCode = -1;

    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        System.err.println("A recoverable exception occurred, retrying." + e.getMessage());
    } catch (IOException e) {
        System.err.println("Failed to download file.");
        e.printStackTrace();
        System.exit(-1);
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

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

    // Deal with the response.
    // Use caution: ensure correct character encoding and is not binary data
    return new String(responseBody);
}

From source file:org.jboss.test.faces.jetty.JettyServerTestCase.java

@Test
public void testHelloPage() throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(
            new URL("http", "localhost", PORT, "/hello-jetty.jsf?name=JettyServer").toExternalForm());

    try {/*from   w  ww  .ja  v a2  s.  c  om*/
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            fail("Method failed: " + method.getStatusLine());
        }

        String responseBodyAsString = method.getResponseBodyAsString();
        assertTrue(responseBodyAsString.contains("Hello, JettyServer!"));

    } finally {
        method.releaseConnection();
    }
}

From source file:org.jboss.test.web.test.WebProgrammaticLoginTestCase.java

/**
 * Test unsuccessful login/*from  w w w  .j av  a2  s. c o  m*/
 * @throws Exception
 */
public void testUnsuccessfulLogin() throws Exception {
    String baseURLNoAuth = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + "/";
    String path = "war1/TestServlet";
    // try to perform programmatic auth without supplying login information.
    HttpMethod indexGet = null;
    try {
        indexGet = new GetMethod(baseURLNoAuth + path + "?operation=login");
        int responseCode = httpConn.executeMethod(indexGet);
        assertTrue("Get Error(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR);
        // assert access to the restricted area of the first application is denied.
        SSOBaseCase.checkAccessDenied(this.httpConn, baseURLNoAuth + "war1/restricted/restricted.html");
        // assert access to the second application is not granted, as no successful login
        // was performed (and therefore no ssoid has been set).
        SSOBaseCase.checkAccessDenied(this.httpConn, baseURLNoAuth + "war2/index.html");
    } finally {
        if (indexGet != null)
            indexGet.releaseConnection();
    }
    // try to perform programmatic auth with no valid username/password.
    path = path + "?operation=login&username=dummy&pass=dummy";
    try {
        indexGet = new GetMethod(baseURLNoAuth + path);
        int responseCode = httpConn.executeMethod(indexGet);
        assertTrue("Get Error(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR);
        // assert access to the restricted applications remains denied.
        SSOBaseCase.checkAccessDenied(this.httpConn, baseURLNoAuth + "war1/restricted/restricted.html");
        SSOBaseCase.checkAccessDenied(this.httpConn, baseURLNoAuth + "war2/index.html");
    } finally {
        if (indexGet != null)
            indexGet.releaseConnection();
    }
}

From source file:org.jboss.test.web.test.WebProgrammaticLoginTestCase.java

/**
 * Test Successful programmatic login in a servlet
 *
 *///from   w  w  w. j a  va  2 s  . c o m
public void testSuccessfulLogin() throws Exception {
    String baseURLNoAuth = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + "/";
    String path1 = "war1/TestServlet?operation=login&username=jduke&pass=theduke";
    HttpMethod indexGet = null;
    HttpMethod indexGet2 = null;
    try {
        indexGet = new GetMethod(baseURLNoAuth + path1);
        int responseCode = httpConn.executeMethod(indexGet);
        assertTrue("Get OK(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_OK);
        // assert access to the restricted are of the first application is now allowed.
        SSOBaseCase.checkAccessAllowed(this.httpConn, baseURLNoAuth + "war1/restricted/restricted.html");
        // assert the sso cookie has been created.
        SSOBaseCase.processSSOCookie(this.httpConn.getState(), baseURLNoAuth, baseURLNoAuth);
        // assert access to the second application is allowed.
        SSOBaseCase.checkAccessAllowed(this.httpConn, baseURLNoAuth + "war2/index.html");

        // perform a programmatic logout and assert access is not allowed anymore.
        indexGet2 = new GetMethod(baseURLNoAuth + "war1/TestServlet?operation=logout");
        responseCode = httpConn.executeMethod(indexGet2);
        assertTrue("Get OK(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_OK);
        SSOBaseCase.checkAccessDenied(this.httpConn, baseURLNoAuth + "war1/restricted/restricted.html");
        SSOBaseCase.checkAccessDenied(this.httpConn, baseURLNoAuth + "war2/index.html");
    } finally {
        if (indexGet != null)
            indexGet.releaseConnection();
        if (indexGet2 != null)
            indexGet2.releaseConnection();
    }
}