Example usage for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY

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

Introduction

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

Prototype

int SC_MOVED_PERMANENTLY

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

Click Source Link

Document

Status code (301) indicating that the resource has permanently moved to a new location, and that future references should use a new URI with their requests.

Usage

From source file:org.tangram.components.UniqueUrlHook.java

@Override
public boolean intercept(TargetDescriptor descriptor, Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Link link = null;//ww w.  j a  va2s  .  c  o m
    try {
        link = linkFactory.createLink(request, response, descriptor.bean, descriptor.action, descriptor.view);
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("intercept() expensive things happen "
                    + ((descriptor.bean == null) ? "" : descriptor.bean.getClass().getName()));
        } // if
    } // try/catch
    if (link != null) {
        // If you run into trouble with encodings, this might be a place to search
        // String decodedUrl = URLDecoder.decode(link.getUrl(), "UTF-8");
        // String requestURI = URLDecoder.decode(request.getRequestURI(), "UTF-8");
        String decodedUrl = link.getUrl();
        final String queryString = request.getQueryString();
        String requestURI = request.getRequestURI()
                + (StringUtils.isBlank(queryString) ? "" : "?" + queryString);
        if (!decodedUrl.equals(requestURI)) {
            LOG.info("render() sending redirect for {} to {}", requestURI, decodedUrl);
            response.setHeader("Location", link.getUrl());
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            return true;
        } // if
    } // if
    return false;
}

From source file:alpine.filters.FqdnForwardFilter.java

/**
 * Forward requests.....// ww  w . j  a va2s.  co  m
 *
 * @param request The request object.
 * @param response The response object.
 * @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}.
 * @throws IOException a IOException
 * @throws ServletException a ServletException
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) request;
    final HttpServletResponse res = (HttpServletResponse) response;

    if (req.getServerName().equals(host)) {
        chain.doFilter(request, response);
        return;
    }

    res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

    StringBuilder sb = new StringBuilder();
    sb.append("http");
    if (req.isSecure()) {
        sb.append("s");
    }
    sb.append("://").append(host);
    if (StringUtils.isNotBlank(req.getPathInfo())) {
        sb.append(req.getPathInfo());
    }
    if (StringUtils.isNotBlank(req.getQueryString())) {
        sb.append("?").append(req.getQueryString());
    }
    res.setHeader("Location", sb.toString());
}

From source file:io.fabric8.apiman.ui.LinkServlet.java

/**
 * Expects JSON data input of the form:/*from w  ww .  j  ava 2 s  .  c  o  m*/
 * {
 *  "access_token": "dXUkkQ7vX6Gv1-d9h1ZTqy_7OM0mAeHOYLV9odpA9r0",
 *  "redirect": "http://localhost:7070/apimanui/api-manager/"
 *  }
 *  It then sets the authToken into the user's session and send
 *  a 301 redirect to the supplied 'redirect' address within the apimanui. 
 *  The browser should follow this and the apimanui will load the
 *  f8-config.js file. This file is served up from the AuthTokenParseServlet
 *  that reads the token from user's session and sets it in the config.js
 *  return, and SSO is accomplished.
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.info(req.getSession().getId());
    String authToken = (String) req.getParameter(ACCESS_TOKEN);
    String redirect = (String) req.getParameter(REDIRECT);
    if (authToken == null) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
        String data = jb.toString();
        JSONObject json = new JSONObject(data);
        authToken = json.getString(ACCESS_TOKEN);
        redirect = json.getString("redirect");
    }
    log.info("301 redirect to " + redirect);
    //Set the authToken in the session
    req.getSession().setAttribute("authToken", authToken);
    //Reply with a redirect to the redirect URL
    resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    resp.setHeader("Location", redirect);
    resp.sendRedirect(redirect);
}

From source file:coria2015.server.ContentServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final URL url;
    IMAGE_URI = "/recipe/image/";
    if (request.getRequestURI().startsWith(IMAGE_URI)) {

        String recipeName = URLDecoder.decode(request.getRequestURI().substring(IMAGE_URI.length()), "UTF-8")
                .replace(" ", "-");
        String name = recipeImages.get(recipeName);
        File file = new File(imagePath, name);
        url = file.toURI().toURL();// w ww.  j  av  a2s  . c o m
    } else {
        url = ContentServlet.class.getResource(format("/web%s", request.getRequestURI()));
    }

    if (url != null) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(url.toExternalForm());
        if (file.getType() == FileType.FOLDER) {
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", format("%sindex.html", request.getRequestURI()));
            return;
        }

        String filename = url.getFile();
        if (filename.endsWith(".html"))
            response.setContentType("text/html");
        else if (filename.endsWith(".png"))
            response.setContentType("image/png");
        else if (filename.endsWith(".css"))
            response.setContentType("text/css");
        response.setStatus(HttpServletResponse.SC_OK);

        final ServletOutputStream out = response.getOutputStream();
        InputStream in = url.openStream();
        byte[] buffer = new byte[8192];
        int read;
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        in.close();
        return;
    }

    // Not found
    error404(request, response);

}

From source file:org.broadleafcommerce.cms.web.URLHandlerFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    String contextPath = request.getContextPath();
    String requestURIWithoutContext;
    if (request.getContextPath() != null) {
        requestURIWithoutContext = request.getRequestURI().substring(request.getContextPath().length());
    } else {/*from  w ww .  java2  s .  c  om*/
        requestURIWithoutContext = request.getRequestURI();
    }

    requestURIWithoutContext = URLDecoder.decode(requestURIWithoutContext, charEncoding);
    URLHandler handler = urlHandlerService.findURLHandlerByURI(requestURIWithoutContext);

    if (handler != null) {
        if (URLRedirectType.FORWARD == handler.getUrlRedirectType()) {
            request.getRequestDispatcher(handler.getNewURL()).forward(request, response);
        } else if (URLRedirectType.REDIRECT_PERM == handler.getUrlRedirectType()) {
            String url = UrlUtil.fixRedirectUrl(contextPath, handler.getNewURL());
            url = fixQueryString(request, url);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", url);
            response.setHeader("Connection", "close");
        } else if (URLRedirectType.REDIRECT_TEMP == handler.getUrlRedirectType()) {
            String url = UrlUtil.fixRedirectUrl(contextPath, handler.getNewURL());
            url = fixQueryString(request, url);
            response.sendRedirect(url);
        }
    } else {
        filterChain.doFilter(request, response);
    }
}

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;//w  w  w  . java 2  s . c  o  m
    }
    // 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:com.citrix.cpbm.portal.fragment.controllers.AbstractServiceProviderLogoController.java

private void logoResponse(String imagePath, String defaultImagePath, HttpServletResponse response) {
    FileInputStream fileinputstream = null;
    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        try {/*from  w ww.ja v a 2  s . c  o m*/
            if (imagePath != null && !imagePath.trim().equals("")) {
                String absoluteImagePath = FilenameUtils.concat(rootImageDir, imagePath);
                fileinputstream = new FileInputStream(absoluteImagePath);
                if (fileinputstream != null) {
                    int numberBytes = fileinputstream.available();
                    byte bytearray[] = new byte[numberBytes];
                    fileinputstream.read(bytearray);
                    response.setContentType("image/" + FilenameUtils.getExtension(imagePath));
                    // TODO:Set Cache headers for browser to force browser to cache to reduce load
                    OutputStream outputStream = response.getOutputStream();
                    response.setContentLength(numberBytes);
                    outputStream.write(bytearray);
                    outputStream.flush();
                    outputStream.close();
                    fileinputstream.close();
                    return;
                }
            }
        } catch (FileNotFoundException e) {
            logger.debug("###File not found in retrieving logo");
        } catch (IOException e) {
            logger.debug("###IO Error in retrieving logo");
        }
    }
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", defaultImagePath);
}

From source file:org.vosao.filter.SiteFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    VosaoContext ctx = VosaoContext.getInstance();
    ctx.setSkipURLs(skipURLs);/* ww  w .j  a  v  a  2 s.  c o  m*/
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String url = httpRequest.getServletPath().toLowerCase();
    if (url.startsWith("/_ah/plugin")) {
        if (processPluginServlet(request, response)) {
            return;
        }
    }
    if (ctx.isSkipUrl(url)) {
        chain.doFilter(request, response);
        return;
    }
    if (url.endsWith("/") && url.length() > 1) {
        httpResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        httpResponse.setHeader("Location", url.substring(0, url.length() - 1));
        httpResponse.setHeader("Connection", "close");
        return;
    }
    if (!isLoggedIn(httpRequest) && servedFromCache(url, httpResponse)) {
        return;
    }
    SeoUrlEntity seoUrl = getDao().getSeoUrlDao().getByFrom(url);
    if (seoUrl != null) {
        httpResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        httpResponse.setHeader("Location", seoUrl.getToLink());
        httpResponse.setHeader("Connection", "close");
        return;
    }
    try {
        if (getDao().getGroupDao().getGuestsGroup() == null) {
            httpResponse.sendRedirect("/setup");
            return;
        }
        PageEntity page = getPage(url, httpRequest);
        if (page != null) {
            renderPage(httpRequest, httpResponse, page, url);
            return;
        }
        if (url.equals("/")) {
            showNoApprovedContent(httpResponse);
            return;
        }
        ConfigEntity config = ctx.getConfig();
        if (!StringUtils.isEmpty(config.getSite404Url())) {
            page = getPage(config.getSite404Url(), httpRequest);
            if (page != null) {
                renderPage(httpRequest, httpResponse, page, url);
            }
        }
        httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } catch (AccessDeniedException e) {
        String userEmail = ctx.getSession().getString(AuthenticationFilter.USER_SESSION_ATTR);

        UserEntity user = getDao().getUserDao().getByEmail(userEmail);
        ConfigEntity config = ctx.getConfig();
        if (user != null) {
            renderMessage(httpResponse, Messages.get("access_denied_page"));
            return;
        }
        if (StringUtils.isEmpty(config.getSiteUserLoginUrl())) {
            renderMessage(httpResponse, Messages.get("login_not_configured"));
            return;
        }
        ctx.getSession().set(AuthenticationFilter.ORIGINAL_VIEW_KEY, httpRequest.getRequestURI());

        httpResponse.sendRedirect(httpRequest.getContextPath() + config.getSiteUserLoginUrl());
    }
}

From source file:no.sesat.search.http.servlet.BoomerangServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {

    // clients must not cache these requests
    res.setHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
    res.setHeader("Pragma", "no-cache"); // for old browsers
    res.setDateHeader("Expires", 0); // to be double-safe

    // entrails is the map of logging information
    final Map<String, Object> entrails = new HashMap<String, Object>();

    // request attribute to keep
    entrails.put("referer", req.getHeader("Referer"));
    entrails.put("method", req.getMethod());
    entrails.put("ipaddress", req.getRemoteAddr());
    entrails.put("user-agent", req.getHeader("User-Agent"));
    entrails.put("user-id", SearchServlet.getCookieValue(req, "SesamID"));
    entrails.put("user", SearchServlet.getCookieValue(req, "SesamUser"));

    if (req.getRequestURI().startsWith(CEREMONIAL)) {

        // ceremonial boomerang
        final StringBuffer url = req.getRequestURL();
        if (null != req.getQueryString()) {
            url.append('?' + req.getQueryString());
        }//from  w ww  .ja va 2s.  c  o  m

        // pick out the entrails
        final int boomerangStart = url.indexOf(CEREMONIAL) + CEREMONIAL.length();

        try {
            final String grub = url.substring(boomerangStart, url.indexOf("/", boomerangStart));
            LOG.debug(grub);

            // the url to return to
            final String destination = url
                    .substring(url.indexOf("/", url.indexOf(CEREMONIAL) + CEREMONIAL.length() + 1) + 1);

            // the grub details to add
            if (0 < grub.length()) {
                final StringTokenizer tokeniser = new StringTokenizer(grub, ";");
                while (tokeniser.hasMoreTokens()) {
                    final String[] entry = tokeniser.nextToken().split("=");
                    entrails.put(entry[0], 1 < entry.length ? entry[1] : entry[0]);
                }
            }
            entrails.put("boomerang", destination);
            kangerooGrub(entrails);

            LOG.debug("Ceremonial boomerang to " + destination.toString());

            if (ROBOTS.matcher(req.getHeader("User-agent")).find()) {
                // robots like permanent redirects. and we're not interested in their clicks so ok to cache.
                res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                res.setHeader("Location", destination.toString());
                res.setHeader("Connection", "close");

            } else {
                // default behaviour for users.
                res.sendRedirect(destination.toString());
            }

        } catch (StringIndexOutOfBoundsException sioobe) {
            // SEARCH-4668
            LOG.error("Boomerang url not to standard --> " + url);
            LOG.debug(sioobe.getMessage(), sioobe);
        }

    } else {

        // hunting boomerang, just grub, and the grub comes as clean parameters.
        final DataModel datamodel = (DataModel) req.getSession().getAttribute(DataModel.KEY);
        entrails.putAll(datamodel.getParameters().getValues());
        kangerooGrub(entrails);

    }

}

From source file:fragment.web.LogoControllerTest.java

private void checkCorrectnessForNullPath() {
    Assert.assertEquals(HttpServletResponse.SC_MOVED_PERMANENTLY, response.getStatus());
}