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

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

Introduction

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

Prototype

public abstract int getStatusCode();

Source Link

Usage

From source file:org.mulgara.resolver.http.HttpContent.java

/**
 * Obtain a valid connection and follow redirects if necessary.
 * /*w w w .  j ava  2s  .c  o  m*/
 * @param methodType request the headders (HEAD) or body (GET)
 * @return valid connection method. Can be null.
 * @throws NotModifiedException  if the content validates against the cache
 * @throws IOException  if there's difficulty communicating with the web site
 */
private HttpMethod establishConnection(int methodType) throws IOException, NotModifiedException {
    if (logger.isDebugEnabled())
        logger.debug("Establishing connection");

    HttpMethod method = getConnectionMethod(methodType);
    assert method != null;
    Header header = null;

    /*
      // Add cache validation headers to the request
      if (lastModifiedMap.containsKey(httpUri)) {
        String lastModified = (String) lastModifiedMap.get(httpUri);
        assert lastModified != null;
        method.addRequestHeader("If-Modified-Since", lastModified);
      }
            
      if (eTagMap.containsKey(httpUri)) {
        String eTag = (String) eTagMap.get(httpUri);
        assert eTag != null;
        method.addRequestHeader("If-None-Match", eTag);
      }
     */

    // Make the request
    if (logger.isDebugEnabled())
        logger.debug("Executing HTTP request");
    connection.open();
    method.execute(state, connection);
    if (logger.isDebugEnabled()) {
        logger.debug("Executed HTTP request, response code " + method.getStatusCode());
    }

    // Interpret the response header
    if (method.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
        // cache has been validated
        throw new NotModifiedException(httpUri);
    } else if (!isValidStatusCode(method.getStatusCode())) {
        throw new UnknownHostException("Unable to obtain connection to " + httpUri + ". Returned status code "
                + method.getStatusCode());
    } else {
        // has a redirection been issued
        int numberOfRedirection = 0;
        while (isRedirected(method.getStatusCode()) && numberOfRedirection <= MAX_NO_REDIRECTS) {

            // release the existing connection
            method.releaseConnection();

            //attempt to follow the redirects
            numberOfRedirection++;

            // obtain the new location
            header = method.getResponseHeader("location");
            if (header != null) {
                try {
                    initialiseSettings(new URL(header.getValue()));
                    if (logger.isInfoEnabled()) {
                        logger.info("Redirecting to " + header.getValue());
                    }

                    // attempt a new connection to this location
                    method = getConnectionMethod(methodType);
                    connection.open();
                    method.execute(state, connection);
                    if (!isValidStatusCode(method.getStatusCode())) {
                        throw new UnknownHostException(
                                "Unable to obtain connection to " + " the redirected site " + httpUri
                                        + ". Returned status code " + method.getStatusCode());
                    }
                } catch (URISyntaxException ex) {
                    throw new IOException(
                            "Unable to follow redirection to " + header.getValue() + " Not a valid URI");
                }
            } else {
                throw new IOException("Unable to obtain redirecting detaild from " + httpUri);
            }
        }
    }

    // Update metadata about the cached document
    Header lastModifiedHeader = method.getResponseHeader("Last-Modified");
    if (lastModifiedHeader != null) {
        logger.debug(lastModifiedHeader.toString());
        assert lastModifiedHeader.getElements().length >= 1;
        assert lastModifiedHeader.getElements()[0].getName() != null;
        assert lastModifiedHeader.getElements()[0].getName() instanceof String;
        // previous code: added to cache
    }

    Header eTagHeader = method.getResponseHeader("Etag");
    if (eTagHeader != null) {
        logger.debug(eTagHeader.toString());
        assert eTagHeader.getElements().length >= 1;
        assert eTagHeader.getElements()[0].getName() != null;
        assert eTagHeader.getElements()[0].getName() instanceof String;
        // previous code: added to cache
    }

    return method;
}

From source file:org.nuxeo.ecm.core.opencmis.impl.client.sso.CasGreeter.java

public String fetchServiceTicket(HttpMethod page) throws HttpException, IOException {
    client.executeMethod(page);//from w  w w.j  ava  2s.c o m
    try {
        if (page.getStatusCode() != HttpStatus.SC_OK) {
            throw new Error("Cannot get login form");
        }
        return extractLoginTicket(page.getResponseBodyAsString());
    } finally {
        page.releaseConnection();
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.client.sso.CasGreeter.java

public String fetchServiceLocation(HttpMethod page) throws HttpException, IOException {
    client.executeMethod(page);//from w  w  w  . ja  v  a 2s  .c o m
    try {
        if (page.getStatusCode() != HttpStatus.SC_OK) {
            throw new Error("Cannot authenticate");
        }
        return extractRedirectLink(page.getResponseBodyAsString());
    } finally {
        page.releaseConnection();
    }
}

From source file:org.nuxeo.ecm.webdav.JackRabbitParallelBench.java

private void createFolder(String folderUri) throws IOException {
    HttpMethod mkcol = new MkColMethod(folderUri);
    client.executeMethod(mkcol);/*w ww . j  a v  a  2 s . c  o m*/

    int status = mkcol.getStatusCode();
    assertEquals(201, status);
}

From source file:org.nuxeo.ecm.webdav.JackRabbitParallelBench.java

private void fillFolder(String folderUri) throws IOException {
    for (int i = 0; i < NUM_DOCS; i++) {
        String uri = folderUri + "/" + i;
        HttpMethod mkcol = new MkColMethod(uri);
        //System.out.println("creating " + uri);
        client.executeMethod(mkcol);// w  ww.  j ava2s  .c  o  m

        int status = mkcol.getStatusCode();
        assertEquals(201, status);
    }
}

From source file:org.nuxeo.ecm.webdav.JackRabbitParallelBench.java

private void deleteObject(String folderUri) throws IOException {
    HttpMethod del = new DeleteMethod(folderUri);
    client.executeMethod(del);// www  .  jav  a 2s. c o  m

    int status = del.getStatusCode();
    assertEquals(204, status);
}

From source file:org.nuxeo.ecm.webdav.ParallelBench.java

private void fillFolder(String folderUri) throws IOException {
    for (int i = 0; i < NUM_DOCS; i++) {
        String uri = folderUri + "/" + i;
        HttpMethod mkcol = new MkColMethod(uri);
        // System.out.println("creating " + uri);
        client.executeMethod(mkcol);/*from  w  w  w .  j a v  a  2s.c o  m*/

        int status = mkcol.getStatusCode();
        assertEquals(201, status);
    }
}

From source file:org.olat.core.commons.modules.glossary.morphService.MorphologicalServiceDEImpl.java

private InputStream retreiveXMLReply(String partOfSpeech, String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair posValues = new NameValuePair(PART_OF_SPEECH_PARAM, partOfSpeech);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (log.isDebug()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + PART_OF_SPEECH_PARAM + "=" + partOfSpeech + "&"
                + GLOSS_TERM_PARAM + "=" + word;
        log.debug("Send GET request to morph-service with URL: " + url);
    }// w  w  w.j  a va 2  s . c om
    method.setQueryString(new NameValuePair[] { posValues, wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (log.isDebug()) {
                log.debug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            log.error("Morphological Service unavailable (404)::" + method.getStatusLine().toString());
        } else {
            log.error("Unexpected HTTP Status::" + method.getStatusLine().toString());
        }
    } catch (Exception e) {
        log.error("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        log.error("URL not found!");
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}

From source file:org.olat.core.commons.modules.glossary.morphService.MorphologicalServiceFRImpl.java

private InputStream retreiveXMLReply(String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (isLogDebugEnabled()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + GLOSS_TERM_PARAM + "=" + word;
        logDebug("Send GET request to morph-service with URL: " + url);
    }/*from w w  w  . ja va 2s.c  om*/
    method.setQueryString(new NameValuePair[] { wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (isLogDebugEnabled()) {
                logDebug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            logError("Morphological Service unavailable (404)::" + method.getStatusLine().toString(), null);
        } else {
            logError("Unexpected HTTP Status::" + method.getStatusLine().toString(), null);
        }
    } catch (Exception e) {
        logError("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        logError("URL not found!", null);
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}

From source file:org.olat.user.propertyhandlers.ICQPropertyHandler.java

/**
 * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map)
 *//*from  ww w.j av  a 2 s.  com*/
@SuppressWarnings({ "unchecked", "unused" })
@Override
public boolean isValid(final FormItem formItem, final Map formContext) {
    boolean result;
    final TextElement textElement = (TextElement) formItem;
    OLog log = Tracing.createLoggerFor(this.getClass());
    if (StringHelper.containsNonWhitespace(textElement.getValue())) {

        // Use an HttpClient to fetch a profile information page from ICQ.
        final HttpClient httpClient = HttpClientFactory.getHttpClientInstance();
        final HttpClientParams httpClientParams = httpClient.getParams();
        httpClientParams.setConnectionManagerTimeout(2500);
        httpClient.setParams(httpClientParams);
        final HttpMethod httpMethod = new GetMethod(ICQ_NAME_VALIDATION_URL);
        final NameValuePair uinParam = new NameValuePair(ICQ_NAME_URL_PARAMETER, textElement.getValue());
        httpMethod.setQueryString(new NameValuePair[] { uinParam });
        // Don't allow redirects since otherwise, we won't be able to get the HTTP 302 further down.
        httpMethod.setFollowRedirects(false);
        try {
            // Get the user profile page
            httpClient.executeMethod(httpMethod);
            final int httpStatusCode = httpMethod.getStatusCode();
            // Looking at the HTTP status code tells us whether a user with the given ICQ name exists.
            if (httpStatusCode == HttpStatus.SC_OK) {
                // ICQ tells us that a user name is valid if it sends an HTTP 200...
                result = true;
            } else if (httpStatusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                // ...and if it's invalid, it sends an HTTP 302.
                textElement.setErrorKey("form.name.icq.error", null);
                result = false;
            } else {
                // For HTTP status codes other than 200 and 302 we will silently assume that the given ICQ name is valid, but inform the user about this.
                textElement.setExampleKey("form.example.icqname.notvalidated", null);
                log.warn("ICQ name validation: Expected HTTP status 200 or 301, but got " + httpStatusCode);
                result = true;
            }
        } catch (final Exception e) {
            // In case of any exception, assume that the given ICQ name is valid (The opposite would block easily upon network problems), and inform the user about
            // this.
            textElement.setExampleKey("form.example.icqname.notvalidated", null);
            log.warn("ICQ name validation: Exception: " + e.getMessage());
            result = true;
        }
    } else {
        result = true;
    }
    log = null;
    return result;
}