Example usage for javax.servlet.http HttpServletResponse SC_TEMPORARY_REDIRECT

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

Introduction

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

Prototype

int SC_TEMPORARY_REDIRECT

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

Click Source Link

Document

Status code (307) indicating that the requested resource resides temporarily under a different URI.

Usage

From source file:org.bonitasoft.web.designer.controller.PreviewController.java

/**
 * Send redirect to the Rest API//from   ww  w .  j  av a2  s .  c o m
 */
@RequestMapping("/preview/{artifact}/API/**")
public void proxyAPICall(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    try {
        String queryString = isEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString();
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.addHeader("Location",
                "/bonita/API/" + RequestMappingUtils.extractPathWithinPattern(request) + queryString);
        response.flushBuffer();
    } catch (IOException e) {
        String message = "Error while redirecting API call";
        logger.error(message, e);
        throw new ServletException(message, e);
    }
}

From source file:org.testdwr.custom.CustomResponseServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    String homePage = request.getContextPath() + request.getServletPath() + "/";

    // Redirect from root dir without trailing slash to with trailing slash
    if (pathInfo == null) {
        response.sendRedirect(homePage);
        return;/*from  w  w w. j  a  va 2  s  . c  om*/
    }
    // Send home page
    else if (pathInfo.equals("/") || pathInfo.startsWith("/page")) {
        InputStream in = getClass().getResourceAsStream(RESOURCE_HELP);
        if (in == null) {
            log.error("Missing file " + RESOURCE_HELP);
            response.sendError(500, "Missing file " + RESOURCE_HELP);
        } else {
            response.setContentType("text/html");
            ServletOutputStream out = response.getOutputStream();
            CopyUtils.copy(in, out);
        }
    }
    // Send empty page
    else if (pathInfo.startsWith("/empty")) {
        response.setContentType("text/html");
    }
    // Handle redirects
    else if (pathInfo.matches("\\/redirect\\/[1-9][0-9][0-9]\\/.*")) {
        String responseCodeStr = pathInfo.substring(10, 10 + 3);
        int responseCode = Integer.parseInt(responseCodeStr);
        String redirectPath = URLDecoder.decode(pathInfo.substring(13), "utf-8");
        redirectPath = request.getContextPath() + request.getServletPath() + redirectPath;

        log.info("Sending " + responseCode + ":" + redirectPath + "(" + pathInfo + ")");
        switch (responseCode) {
        case HttpServletResponse.SC_MULTIPLE_CHOICES:
        case HttpServletResponse.SC_MOVED_PERMANENTLY:
        case HttpServletResponse.SC_FOUND:
        case HttpServletResponse.SC_SEE_OTHER:
            response.setHeader("Location", "/" + redirectPath);
            response.setStatus(responseCode);
            break;

        case HttpServletResponse.SC_TEMPORARY_REDIRECT:
            response.sendRedirect(redirectPath);
            break;

        default:
            response.sendError(responseCode, "/" + redirectPath);
            break;
        }
    }
    // Send 404
    else {
        response.sendError(404);
    }
}

From source file:org.apache.cocoon.servletservice.HttpServletResponseBufferingWrapper.java

public void sendRedirect(String location) throws IOException {
    if (isCommitted())
        throw new IllegalStateException(ALREADY_COMMITTED_EXCEPTION);
    super.sendRedirect(location);
    statusCode = HttpServletResponse.SC_TEMPORARY_REDIRECT;
}

From source file:com.google.ie.common.openid.appengine.Openid4javaFetcher.java

private static boolean isRedirect(int responseCode) {
    switch (responseCode) {
    case HttpServletResponse.SC_MOVED_PERMANENTLY:
    case HttpServletResponse.SC_MOVED_TEMPORARILY:
    case HttpServletResponse.SC_SEE_OTHER:
    case HttpServletResponse.SC_TEMPORARY_REDIRECT:
        return true;
    default://from   w  w w. j  a  v a  2s  .co m
        return false;
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    response.setCharacterEncoding("UTF-8");
    String htmlEscapedUri = HtmlQuoting.quoteHtmlChars(request.getRequestURI());

    if (htmlEscapedUri == null) {
        htmlEscapedUri = "/";
    }//w w  w . j  a v a 2s . c  o  m

    String uriWithQueryString = htmlEscapedUri;
    String htmlEscapedUriWithQueryString = htmlEscapedUri;

    String queryString = request.getQueryString();
    if (queryString != null && !queryString.isEmpty()) {
        String reqEncoding = request.getCharacterEncoding();
        if (reqEncoding == null || reqEncoding.isEmpty()) {
            reqEncoding = "ISO-8859-1";
        }
        Charset encoding = Charset.forName(reqEncoding);
        List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding);
        String urlEncodedQueryString = URLEncodedUtils.format(params, encoding);
        uriWithQueryString += "?" + urlEncodedQueryString;
        htmlEscapedUriWithQueryString = HtmlQuoting
                .quoteHtmlChars(request.getRequestURI() + "?" + urlEncodedQueryString);
    }

    RMWebApp rmWebApp = injector.getInstance(RMWebApp.class);
    rmWebApp.checkIfStandbyRM();
    if (rmWebApp.isStandby() && shouldRedirect(rmWebApp, htmlEscapedUri)) {

        String redirectPath = rmWebApp.getRedirectPath();

        if (redirectPath != null && !redirectPath.isEmpty()) {
            redirectPath += uriWithQueryString;
            String redirectMsg = "This is standby RM. The redirect url is: " + htmlEscapedUriWithQueryString;
            PrintWriter out = response.getWriter();
            out.println(redirectMsg);
            response.setHeader("Location", redirectPath);
            response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
            return;
        } else {
            boolean doRetry = true;
            String retryIntervalStr = request.getParameter(YarnWebParams.NEXT_REFRESH_INTERVAL);
            int retryInterval = 0;
            if (retryIntervalStr != null) {
                try {
                    retryInterval = Integer.parseInt(retryIntervalStr.trim());
                } catch (NumberFormatException ex) {
                    doRetry = false;
                }
            }
            int next = calculateExponentialTime(retryInterval);

            String redirectUrl = appendOrReplaceParamter(path + uriWithQueryString,
                    YarnWebParams.NEXT_REFRESH_INTERVAL + "=" + (retryInterval + 1));
            if (redirectUrl == null || next > MAX_SLEEP_TIME) {
                doRetry = false;
            }
            String redirectMsg = doRetry
                    ? "Can not find any active RM. Will retry in next " + next + " seconds."
                    : "There is no active RM right now.";
            redirectMsg += "\nHA Zookeeper Connection State: " + rmWebApp.getHAZookeeperConnectionState();
            PrintWriter out = response.getWriter();
            out.println(redirectMsg);
            if (doRetry) {
                response.setHeader("Refresh", next + ";url=" + redirectUrl);
                response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
            }
        }
        return;
    } else if (ahsEnabled) {
        String ahsRedirectUrl = ahsRedirectPath(uriWithQueryString, rmWebApp);
        if (ahsRedirectUrl != null) {
            response.setHeader("Location", ahsRedirectUrl);
            response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
            return;
        }
    }

    super.doFilter(request, response, chain);
}

From source file:org.dspace.app.xmlui.aspect.general.PageNotFoundTransformer.java

private boolean isRedirect() {
    final HttpServletResponse response = (HttpServletResponse) objectModel
            .get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
    try {//from   w  w  w . j  a va  2  s. c om
        return ((int) FieldUtils.readField(response, "statusCode",
                true)) == HttpServletResponse.SC_TEMPORARY_REDIRECT;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.bedework.calsvc.scheduling.hosts.IscheduleClient.java

/** See if we have a url for the service. If not discover the real one.
 *
 * @param hi//from  w w  w .  j  a v  a 2 s  .  c om
 */
private void discover(final HostInfo hi) throws CalFacadeException {
    if (hi.getIScheduleUrl() != null) {
        return;
    }

    /* For the moment we'll try to find it via .well-known. We may have to
     * use DNS SRV lookups
     */
    //    String domain = hi.getHostname();

    //  int lpos = domain.lastIndexOf(".");
    //int lpos2 = domain.lastIndexOf(".", lpos - 1);

    //    if (lpos2 > 0) {
    //    domain = domain.substring(lpos2 + 1);
    //}

    int rcode = 0;

    BasicHttpClient cio = null;

    try {
        /*
        // XXX ioptest fix - remove
        String url;
        if ("example.com".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else if ("ken.name".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else {
          url = "https://" + hi.getHostname() + "/.well-known/ischedule";
        }
        */

        final String scheme;
        final String port;

        if (hi.getPort() == 0) {
            port = "";
        } else {
            port = ":" + hi.getPort();
        }

        if (hi.getSecure()) {
            scheme = "https://";
        } else {
            scheme = "http://";
        }

        String url = scheme + hi.getHostname() + port + "/.well-known/ischedule";

        cio = getCio(url);

        for (int redirects = 0; redirects < 10; redirects++) {
            rcode = cio.sendRequest("GET", url + "?action=capabilities", null, "application/xml", 0, null);

            if ((rcode == HttpServletResponse.SC_MOVED_PERMANENTLY)
                    || (rcode == HttpServletResponse.SC_MOVED_TEMPORARILY)
                    || (rcode == HttpServletResponse.SC_TEMPORARY_REDIRECT)) {
                //boolean permanent = rcode == HttpServletResponse.SC_MOVED_PERMANENTLY;

                Header locationHeader = cio.getFirstHeader("location");
                if (locationHeader != null) {
                    if (debug) {
                        debugMsg("Got redirected to " + locationHeader.getValue() + " from " + url);
                    }

                    String newLoc = locationHeader.getValue();
                    int qpos = newLoc.indexOf("?");

                    cioTable.remove(url);

                    if (qpos < 0) {
                        url = newLoc;
                    } else {
                        url = newLoc.substring(0, qpos);
                    }

                    cio.release();

                    // Try again
                    continue;
                }
            }

            if (rcode != HttpServletResponse.SC_OK) {
                // The response is invalid and did not provide the new location for
                // the resource.  Report an error or possibly handle the response
                // like a 404 Not Found error.
                if (debug) {
                    error("Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);

                    if (cio.getResponseContentLength() != 0) {
                        InputStream is = cio.getResponseBodyAsStream();

                        LineNumberReader in = new LineNumberReader(new InputStreamReader(is));

                        error("Content: ==========================");
                        while (true) {
                            String l = in.readLine();
                            if (l == null) {
                                break;
                            }

                            error(l);
                        }
                        error("End content: ==========================");
                    }
                }

                throw new CalFacadeException(
                        "Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);
            }

            /* Should have a capabilities record. */

            hi.setIScheduleUrl(url);
            return;
        }

        if (debug) {
            error("Too many redirects: Got response " + rcode + ", host " + hi.getHostname() + " and url "
                    + url);
        }

        throw new CalFacadeException("Too many redirects on " + url);
    } catch (CalFacadeException cfe) {
        throw cfe;
    } catch (Throwable t) {
        if (debug) {
            error(t);
        }

        throw new CalFacadeException(t);
    } finally {
        try {
            if (cio != null) {
                cio.release();
            }
        } catch (Throwable t) {
        }
    }
}

From source file:com.kurento.kmf.content.internal.base.AbstractHttpContentSession.java

/**
 * Provide an HTTP response, depending of which redirect strategy is used:
 * it could a redirect (HTTP 307, Temporary Redirect), or a tunneled
 * response using the Streaming Proxy.//  w w w.  j a va 2s. c  o  m
 * 
 * @param url
 *            Content URL
 * @throws ContentException
 *             Exception in the media server
 */
private void answerActivateMediaRequest4SimpleHttpConfigurationWithRedirect(String url) {
    try {
        HttpServletResponse response = (HttpServletResponse) initialAsyncCtx.getResponse();
        getLogger().info("Sending redirect to " + url);
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.setHeader("Location", url);

    } catch (Throwable t) {
        throw new KurentoMediaFrameworkException(t.getMessage(), t, 20013);
    } finally {
        initialAsyncCtx.complete();
        initialAsyncCtx = null;
    }
}

From source file:com.jsmartframework.web.manager.ServletControl.java

private void sendRedirect(String path, HttpServletRequest request, HttpServletResponse response,
        boolean authNeeded) throws IOException, ServletException {
    if (request.getServletPath().equals(path)) {
        String url = HANDLER.getForwardPath(path);
        if (url == null) {
            LOGGER.log(Level.SEVERE, "Could not find JSP page for path [" + path + "]");
            return;
        }//  w  w  w .  j  a  v a 2s  .c om

        // Generate web security token to prevent CSRF attack
        HANDLER.generateWebSecurityToken(request, response);

        // Use Forward request internally case is the same page
        request.getRequestDispatcher(url).forward(request, response);

    } else {
        // Use Redirect response case page had changed (Do not use status 302 once cookies are not set)
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.setHeader("Location", getRedirectPath(path, request, authNeeded));
    }
}