Example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY

List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY.

Prototype

int SC_MOVED_PERMANENTLY

To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_PERMANENTLY.

Click Source Link

Document

<tt>301 Moved Permanently</tt> (HTTP/1.0 - RFC 1945)

Usage

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

private boolean isRedirected(int status) {
    return (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_TEMPORARILY
            || status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_SEE_OTHER);
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;/*from   w w  w .  ja v a2 s . c  o m*/
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

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

/**
 * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map)
 *///from  ww w .j a  v  a 2  s .  co m
@SuppressWarnings({ "unchecked" })
@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 MSN.
        final HttpClient httpClient = HttpClientFactory.getHttpClientInstance();
        final HttpClientParams httpClientParams = httpClient.getParams();
        httpClientParams.setConnectionManagerTimeout(2500);
        httpClient.setParams(httpClientParams);
        final HttpMethod httpMethod = new GetMethod(MSN_NAME_VALIDATION_URL);
        final NameValuePair idParam = new NameValuePair(MSN_NAME_URL_PARAMETER, textElement.getValue());
        httpMethod.setQueryString(new NameValuePair[] { idParam });
        // Don't allow redirects since otherwise, we won't be able to get the correct status
        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 MSN name exists.
            if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
                // If the user exists, we get a 301...
                result = true;
            } else if (httpStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                // ...and if the user doesn't exist, MSN sends a 500.
                textElement.setErrorKey("form.name.msn.error", null);
                result = false;
            } else {
                // For HTTP status codes other than 301 and 500 we will assume that the given MSN name is valid, but inform the user about this.
                textElement.setExampleKey("form.example.msnname.notvalidated", null);
                log.warn("MSN name validation: Expected HTTP status 301 or 500, but got " + httpStatusCode);
                result = true;
            }
        } catch (final Exception e) {
            // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about
            // this.
            textElement.setExampleKey("form.example.msnname.notvalidated", null);
            log.warn("MSN name validation: Exception: " + e.getMessage());
            result = true;
        }
    } else {
        result = true;
    }
    log = null;
    return result;
}

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

/**
 * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map)
 *//*from  w  w  w .  j a v  a  2  s  .c o m*/
@SuppressWarnings({ "unused", "unchecked" })
@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())) {
        final HttpClient httpClient = HttpClientFactory.getHttpClientInstance();
        final HttpClientParams httpClientParams = httpClient.getParams();
        httpClientParams.setConnectionManagerTimeout(2500);
        httpClient.setParams(httpClientParams);
        try {
            // Could throw IllegalArgumentException if argument is not a valid url
            // (e.g. contains whitespaces)
            final HttpMethod httpMethod = new GetMethod(XING_NAME_VALIDATION_URL + textElement.getValue());
            // Don't allow redirects since otherwise, we won't be able to get the correct status
            httpMethod.setFollowRedirects(false);
            // 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 Xing name exists.
            if (httpStatusCode == HttpStatus.SC_OK) {
                // If the user exists, we get a 200...
                result = true;
            } else if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
                // ... and if he doesn't exist, we get a 301.
                textElement.setErrorKey("form.name.xing.error", null);
                result = false;
            } else {
                // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user
                // about this.
                textElement.setExampleKey("form.example.xingname.notvalidated", null);
                log.warn("Xing name validation: Expected HTTP status 200 or 301, but got " + httpStatusCode);
                result = true;
            }
        } catch (final IllegalArgumentException e) {
            // The xing name is not url compatible (e.g. contains whitespaces)
            textElement.setErrorKey("form.xingname.notvalid", null);
            result = false;
        } catch (final Exception e) {
            // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about
            // this.
            textElement.setExampleKey("form.example.xingname.notvalidated", null);
            log.warn("Xing name validation: Exception: " + e.getMessage());
            result = true;
        }
    } else {
        result = true;
    }
    log = null;
    return result;
}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * convenience routine missing from http library
 */// w  ww .j a  va  2s.c  o m
static boolean isRedirect(int rc) {
    return (rc == HttpStatus.SC_MOVED_PERMANENTLY || rc == HttpStatus.SC_MOVED_TEMPORARILY
            || rc == HttpStatus.SC_SEE_OTHER || rc == HttpStatus.SC_TEMPORARY_REDIRECT);
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

private int computeStatus(int status) {
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_NOT_ACCEPTABLE:
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
    case HttpStatus.SC_REQUEST_TIMEOUT:
    case HttpStatus.SC_CONFLICT:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_LENGTH_REQUIRED:
    case HttpStatus.SC_PRECONDITION_FAILED:
    case HttpStatus.SC_REQUEST_TOO_LONG:
    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
    case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
    case HttpStatus.SC_EXPECTATION_FAILED:
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
    case HttpStatus.SC_METHOD_FAILURE:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
    case HttpStatus.SC_LOCKED:
    case HttpStatus.SC_FAILED_DEPENDENCY:
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
    case HttpStatus.SC_NOT_IMPLEMENTED:
    case HttpStatus.SC_BAD_GATEWAY:
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
    case HttpStatus.SC_GATEWAY_TIMEOUT:
    case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return 0;
    case HttpStatus.SC_CONTINUE:
    case HttpStatus.SC_SWITCHING_PROTOCOLS:
    case HttpStatus.SC_PROCESSING:
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
    case HttpStatus.SC_NO_CONTENT:
    case HttpStatus.SC_RESET_CONTENT:
    case HttpStatus.SC_PARTIAL_CONTENT:
    case HttpStatus.SC_MULTI_STATUS:
    case HttpStatus.SC_MULTIPLE_CHOICES:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_NOT_MODIFIED:
    case HttpStatus.SC_USE_PROXY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return 1;
    default:/* w  w w  . j  ava  2 s.c  om*/
        return 1;
    }
}

From source file:org.soaplab.gowlab.GowlabJob.java

/**************************************************************************
 * It evaluates the status in 'httpMethod'.
 *
 * If the status indicates that everything went fine, it passes
 * the response to the 'sendResult' method, and set the new job
 * status as successfully completed.//from  w  ww.  ja  v  a  2 s. co  m
 *
 * Otherwise it reports error to the reporter and changes job status
 * reflecting the error.
 **************************************************************************/
protected void processResponse() throws SoaplabException {

    if (httpMethod.getStatusCode() >= HttpStatus.SC_MOVED_PERMANENTLY) {

        // something wrong
        error(httpMethod.getStatusLine().toString());
        reporter.getState().set(JobState.TERMINATED_BY_ERROR, "" + httpMethod.getStatusCode());
        reporter.getState().setDescription(httpMethod.getStatusText());

    } else {
        // okay
        sendResults();
        reporter.getState().set(JobState.COMPLETED, "" + HttpStatus.SC_OK);
    }
}

From source file:org.vamdc.taverna.vamdc_taverna_suite.common.UWSCaller.java

/**
 * @param filename/*from w w  w  .ja va2 s  .  com*/
 * @param strURL
 * @param append
 * @return
 * @throws Exception
 */
private static String getDetails(File input, String strURL, String append) throws Exception {
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream
    // Per default, the request content needs to be buffered
    // in order to determine its length.
    // Request body buffering can be avoided when
    // content length is explicitly specified

    post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");

    post.setFollowRedirects(false);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();

    try {
        //httpclient.
        int result = httpclient.executeMethod(post);
        int statuscode = post.getStatusCode();

        if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                || (statuscode == HttpStatus.SC_SEE_OTHER)
                || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

            Header header = post.getResponseHeader("location");
            System.out.println("   :  Header  :  " + header);
            if (header != null) {
                String newuri = header.getValue();
                if ((newuri == null) || (newuri.equals("")))
                    newuri = "/";
                return newuri;
            } else {
                return null;
            }
        } else {
            System.out.println(post.getResponseBodyAsString());
        }
    } finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
    }
    return null;
}

From source file:org.wso2.appfactory.integration.test.utils.external.HttpHandler.java

/**
 * This method is used to retrieve the redirection location from response header
 * as the request will results in either 301 or 302 status code.
 * @param url/*from  ww w.  j  a  v a2 s  . c  om*/
 * @return
 * @throws IOException
 */
public static String getRedirectionUrl(String url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    HttpResponse response = httpclient.execute(httpPost);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
        return response.getFirstHeader(HTTPConstants.HEADER_LOCATION).getValue();
    }
    return null;
}

From source file:org.ybygjy.httpclient.FormLoginDemo.java

public static void main(String[] args) throws Exception {

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the RFC2109
    // We have to resort to using compatibility cookie policy

    GetMethod authget = new GetMethod("/org.ybygjy.web.servlet.HttpClientServlet");

    client.executeMethod(authget);//  www  . j  ava 2 s  .  co  m
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
    System.out.println("Initial set of cookies:");
    if (initcookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < initcookies.length; i++) {
            System.out.println("- " + initcookies[i].toString());
        }
    }

    PostMethod authpost = new PostMethod("/org.ybygjy.web.servlet.HttpClientServlet");
    // Prepare login parameters
    NameValuePair action = new NameValuePair("action", "login");
    NameValuePair url = new NameValuePair("url", "/index.html");
    NameValuePair userid = new NameValuePair("UserId", "userid");
    NameValuePair password = new NameValuePair("Password", "password");
    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password });

    client.executeMethod(authpost);
    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is 
    // by finding a session cookie
    Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:");
    if (logoncookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < logoncookies.length; i++) {
            System.out.println("- " + logoncookies[i].toString());
        }
    }
    // Usually a successful form-based login results in a redicrect to 
    // another url
    int statuscode = authpost.getStatusCode();
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = authpost.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }
            System.out.println("Redirect target: " + newuri);
            GetMethod redirect = new GetMethod(newuri);

            client.executeMethod(redirect);
            System.out.println("Redirect: " + redirect.getStatusLine().toString());
            // release any connection resources used by the method
            redirect.releaseConnection();
        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    }
}