Example usage for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY

List of usage examples for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY.

Prototype

int SC_MOVED_TEMPORARILY

To view the source code for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY.

Click Source Link

Document

Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource.

Usage

From source file:org.apache.sling.launchpad.webapp.integrationtest.login.RedirectOnLogoutTest.java

/**
 * Test SLING-1847//w  ww  .  j  a  va 2  s  . c  o  m
 * @throws Exception
 */
@Test
public void testRedirectToResourceAfterLogout() throws Exception {
    //login
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "admin"));
    params.add(new NameValuePair("j_password", "admin"));
    H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY,
            params, null);

    //...and then...logout with a resource redirect
    String locationAfterLogout = HttpTest.SERVLET_CONTEXT + "/system/sling/info.sessionInfo.json";
    final GetMethod get = new GetMethod(HttpTest.HTTP_BASE_URL + "/system/sling/logout");
    NameValuePair[] logoutParams = new NameValuePair[1];
    logoutParams[0] = new NameValuePair("resource", locationAfterLogout);
    get.setQueryString(logoutParams);

    get.setFollowRedirects(false);
    final int status = H.getHttpClient().executeMethod(get);
    assertEquals("Expected redirect", HttpServletResponse.SC_MOVED_TEMPORARILY, status);
    Header location = get.getResponseHeader("Location");
    assertEquals(HttpTest.HTTP_BASE_URL + locationAfterLogout, location.getValue());
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.login.SelectorRedirectOnLoginErrorTest.java

/**
 * Test SLING-2165.  Login Error should redirect back to the referrer
 * login page./*from www .ja va  2 s  . co  m*/
 *
 * @throws Exception
 */
public void testRedirectToSelectorLoginFormAfterLoginError() throws Exception {
    //login failure
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "___bogus___"));
    params.add(new NameValuePair("j_password", "not_a_real_user"));
    final String loginPageUrl = String.format("%s/system/sling/selector/login", HTTP_BASE_URL);
    PostMethod post = (PostMethod) assertPostStatus(HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_MOVED_TEMPORARILY, params, null, loginPageUrl);

    final Header locationHeader = post.getResponseHeader("Location");
    String location = locationHeader.getValue();
    int queryStrStart = location.indexOf('?');
    if (queryStrStart != -1) {
        location = location.substring(0, queryStrStart);
    }
    assertEquals("Expected to remain on the selector/login page", loginPageUrl, location);
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.login.SelectorRedirectOnLoginErrorTest.java

/**
 * Test SLING-2165.  Login Error should redirect back to the referrer
 * login page.//from  ww w.  j  a  v a2 s.co  m
 *
 * @throws Exception
 */
public void testRedirectToOpenIDLoginFormAfterLoginError() throws Exception {
    //login failure
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("openid_identifier", "___bogus___"));
    final String loginPageUrl = String.format("%s/system/sling/openid/login", HTTP_BASE_URL);
    PostMethod post = (PostMethod) assertPostStatus(HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_MOVED_TEMPORARILY, params, null, loginPageUrl);

    final Header locationHeader = post.getResponseHeader("Location");
    String location = locationHeader.getValue();
    int queryStrStart = location.indexOf('?');
    if (queryStrStart != -1) {
        location = location.substring(0, queryStrStart);
    }
    assertEquals("Expected to remain on the openid/login page", loginPageUrl, location);
}

From source file:org.apache.sling.servlethelpers.MockSlingHttpServletResponse.java

@Override
public void sendRedirect(String location) {
    setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    setHeader("Location", location);
}

From source file:org.apache.sling.servlethelpers.MockSlingHttpServletResponseTest.java

@Test
public void testRedirect() throws Exception {
    response.sendRedirect("/location.html");
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus());
    assertEquals("/location.html", response.getHeader("Location"));
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given
 * {@link HttpServletResponse}.// w w w  . j  a  v  a2  s  .  c o m
 *
 * @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
 * @throws IOException              Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException         Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient;
    httpClient = createClientWithLogin();
    httpMethodProxyRequest.setFollowRedirects(false);

    // 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(HEADER_LOCATION).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + HEADER_LOCATION + " 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) {
            httpServletResponse
                    .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, 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(HEADER_CONTENT_LENGTH, 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")) {
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

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

    // FIXME We should handle both String and bytes response in the same way:
    String response = null;
    byte[] bodyBytes = null;

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

    if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) {
        LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response);
    } else {
        LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode);
    }

    // Send the content to the client
    if (response != null) {
        httpServletResponse.getWriter().write(response);
    } else if (bodyBytes != null) {
        httpServletResponse.getOutputStream().write(bodyBytes);
    } else {
        IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream());
    }
}

From source file:org.codehaus.groovy.grails.web.metaclass.RedirectDynamicMethod.java

private Object redirectResponse(String serverBaseURL, String actualUri, HttpServletRequest request,
        HttpServletResponse response, boolean permanent) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Dynamic method [redirect] forwarding request to [" + actualUri + "]");
    }/*from   www . j  a v  a 2  s  .  c  o  m*/

    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing redirect with response [" + response + "]");
    }
    String processedActualUri = processedUrl(actualUri, request);
    String absoluteURL = processedActualUri.contains("://") ? processedActualUri
            : serverBaseURL + processedActualUri;
    String redirectUrl = useJessionId ? response.encodeRedirectURL(absoluteURL) : absoluteURL;
    int status = permanent ? HttpServletResponse.SC_MOVED_PERMANENTLY
            : HttpServletResponse.SC_MOVED_TEMPORARILY;

    response.setStatus(status);
    response.setHeader(HttpHeaders.LOCATION, redirectUrl);

    if (redirectListeners != null) {
        for (RedirectEventListener redirectEventListener : redirectListeners) {
            redirectEventListener.responseRedirected(redirectUrl);
        }
    }

    request.setAttribute(GRAILS_REDIRECT_ISSUED, processedActualUri);
    return null;
}

From source file:org.entando.entando.plugins.jpoauthclient.aps.system.services.client.ProviderConnectionManager.java

/**
 * Handle an exception that occurred while processing an HTTP request.
 * Depending on the exception, either send a response, redirect the client
 * or propagate an exception.//from   w  ww.j av a2s . c  o  m
 */
public void handleException(ApiMethodRequestBean bean, Exception e, HttpServletRequest request,
        HttpServletResponse response, OAuthConsumer consumer, boolean redirectOAuthErrorPage)
        throws IOException, ServletException {
    if (e instanceof RedirectException) {
        RedirectException redirect = (RedirectException) e;
        String targetURL = redirect.getTargetURL();
        if (targetURL != null) {
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", targetURL);
        }
    } else if (e instanceof OAuthProblemException) {
        OAuthProblemException p = (OAuthProblemException) e;
        String problem = p.getProblem();
        List<String> recoverableProblems = Arrays.asList(RECOVERABLE_PROBLEMS);
        if (consumer != null && recoverableProblems.contains(problem)) {
            try {
                CookieMap cookies = new CookieMap(request, response);
                OAuthAccessor accessor = this.newAccessor(consumer, cookies);
                this.getAccessToken(bean, request, cookies, accessor);
            } catch (Exception e2) {
                handleException(bean, e2, request, response, null, redirectOAuthErrorPage);
            }
        } else if (redirectOAuthErrorPage) {
            try {
                StringWriter s = new StringWriter();
                PrintWriter pw = new PrintWriter(s);
                e.printStackTrace(pw);
                pw.flush();
                p.setParameter("stack trace", s.toString());
            } catch (Exception rats) {
                //nothing to catch
            }
            response.setStatus(p.getHttpStatusCode());
            response.resetBuffer();
            request.setAttribute("OAuthProblemException", p);
            request.getRequestDispatcher("/WEB-INF/plugins/jpoauthclient/OAuthProblemException.jsp")
                    .forward(request, response);
        }
    } else if (e instanceof IOException) {
        throw (IOException) e;
    } else if (e instanceof ServletException) {
        throw (ServletException) e;
    } else if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
    } else {
        throw new ServletException(e);
    }
}

From source file:org.everit.authentication.http.form.ecm.tests.FormAuthenticationServletTestComponent.java

private void login(final HttpContext httpContext, final String username, final String password,
        final String expectedLocation) throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(loginActionUrl);
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("username", username));
    parameters.add(new BasicNameValuePair("password", password));
    parameters.add(new BasicNameValuePair("successUrl", LOGIN_SUCCESS_ALIAS));
    parameters.add(new BasicNameValuePair("failedUrl", LOGIN_FAILED_ALIAS));
    HttpEntity entity = new UrlEncodedFormEntity(parameters);
    httpPost.setEntity(entity);//from w  w  w .j av a2  s.  c o m
    HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
    Assert.assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, httpResponse.getStatusLine().getStatusCode());
    Header locationHeader = httpResponse.getFirstHeader("Location");
    Assert.assertEquals(expectedLocation, locationHeader.getValue());
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

/**
 * Handles an error status code.//from  www  .  jav  a 2  s  .  co m
 * 
 * @return true if we've forwarded to an error page.
 */
private boolean handleErrorStatus(CauchoRequest request, CauchoResponse response, int code, String message)
        throws ServletException, IOException {
    if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_MOVED_TEMPORARILY
            || code == HttpServletResponse.SC_NOT_MODIFIED)
        return false;

    if (request.getRequestDepth(0) > 16)
        return false;

    else if (request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI) != null) {
        return false;
    }

    response.killCache();

    String location = getErrorPage(code);

    if (location == null)
        location = _defaultLocation;

    WebApp webApp = getWebApp();

    if (webApp == null && _host == null)
        return false;

    if (location != null && !location.equals(request.getRequestURI())) {
        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(code));
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
        request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());

        String servletName = getServletName(request);

        if (servletName != null)
            request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName);

        try {
            RequestDispatcher disp = null;
            // can't use filters because of error pages due to filters
            // or security.
            if (webApp != null)
                disp = webApp.getRequestDispatcher(location);
            else if (_host != null)
                disp = _host.getWebAppContainer().getRequestDispatcher(location);

            // disp.forward(request, this, "GET", false);

            if (disp != null) {
                ((RequestDispatcherImpl) disp).error(request, response);
            } else
                return false;
        } catch (Throwable e) {
            sendServletError(e, request, response);
        }

        return true;
    }

    return false;
}