Example usage for javax.servlet.http HttpServletResponse sendRedirect

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

Introduction

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

Prototype

public void sendRedirect(String location) throws IOException;

Source Link

Document

Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.

Usage

From source file:io.lavagna.web.api.SetupController.java

@RequestMapping(value = "/setup/api/import", method = RequestMethod.POST)
public void importLavagna(@RequestParam("file") MultipartFile file, HttpServletRequest req,
        HttpServletResponse res) throws IOException {

    // TODO: move to a helper, as it has the same code as the one in the ExportImportController
    Path tempFile = Files.createTempFile(null, null);
    try {//from  ww w. j  a v  a  2 s.c om
        try (InputStream is = file.getInputStream(); OutputStream os = Files.newOutputStream(tempFile)) {
            StreamUtils.copy(is, os);
        }
        exportImportService2.importData(true, tempFile);
    } finally {
        Files.delete(tempFile);
    }
    //

    res.sendRedirect(req.getServletContext().getContextPath());
}

From source file:com.amazonaws.services.kinesis.aggregators.app.ShowConfigFileServlet.java

@Override
protected void doAction(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w  ww  . j ava  2s  .c  om
        String configUrl = System.getProperty(AggregatorsConstants.CONFIG_URL_PARAM);
        String url = null;
        if (configUrl == null) {
            response.setStatus(404);
        } else {
            url = ConfigFileUtils.makeConfigFileURL(configUrl);
            LOG.info(String.format("Sending Redirect for Config File to S3 Temporary URL %s", url));

            response.setHeader("Access-Control-Allow-Origin", "*");
            response.sendRedirect(url);
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.authenticate.LoginExternalAuthSetup.java

/**
 * Write down the referring page, record that we are logging in, and
 * redirect to the external authorization server URL.
 *//*  ww  w .  ja  v a2  s  .  co m*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    storeTheReferringPage(req);

    LoginProcessBean.getBean(req).setState(LoginProcessBean.State.LOGGING_IN);

    String returnUrl = buildReturnUrl(req);
    String redirectUrl = ExternalAuthHelper.getHelper(req).buildExternalAuthRedirectUrl(returnUrl);

    if (redirectUrl == null) {
        complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, messageLoginFailed(req));
    }

    log.debug("redirecting to '" + redirectUrl + "'");
    resp.sendRedirect(redirectUrl);
}

From source file:net.sourceforge.vulcan.web.ProjectFileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String pathInfo = request.getPathInfo();

    if (isBlank(pathInfo)) {
        response.sendRedirect(request.getContextPath());
        return;//from ww  w .  java  2s  .  c om
    }

    final PathInfo projPathInfo = getProjectNameAndBuildNumber(pathInfo);

    if (isBlank(projPathInfo.projectName)) {
        response.sendRedirect(request.getContextPath());
        return;
    }

    final ProjectConfigDto projectConfig;

    try {
        projectConfig = projectManager.getProjectConfig(projPathInfo.projectName);
    } catch (NoSuchProjectException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    final String requestURI = request.getRequestURI();

    if (projPathInfo.buildNumber < 0) {
        redirectWithBuildNumber(response, projPathInfo, requestURI);
        return;
    }

    final ProjectStatusDto buildOutcome = buildManager.getStatusByBuildNumber(projPathInfo.projectName,
            projPathInfo.buildNumber);

    if (buildOutcome == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No such build " + projPathInfo.buildNumber + " for project Project.");
        return;
    }

    final String workDir;

    if (StringUtils.isNotBlank(buildOutcome.getWorkDir())) {
        workDir = buildOutcome.getWorkDir();
    } else {
        workDir = projectConfig.getWorkDir();
    }

    final File file = getFile(workDir, pathInfo, true);

    if (!file.exists()) {
        if (shouldFallback(request, workDir, file)) {
            response.sendRedirect(getFallbackParentPath(request, workDir));
            return;
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } else if (!file.canRead()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    } else if (file.isDirectory()) {
        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(requestURI + "/");
            return;
        }

        final File[] files = getDirectoryListing(file);

        request.setAttribute(Keys.DIR_PATH, pathInfo);
        request.setAttribute(Keys.FILE_LIST, files);

        request.getRequestDispatcher(Keys.FILE_LIST_VIEW).forward(request, response);
        return;
    }

    setContentType(request, response, pathInfo);

    final Date lastModifiedDate = new Date(file.lastModified());

    if (!checkModifiedSinceHeader(request, lastModifiedDate)) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);

    setLastModifiedDate(response, lastModifiedDate);

    response.setContentLength((int) file.length());

    final FileInputStream fis = new FileInputStream(file);
    final ServletOutputStream os = response.getOutputStream();

    sendFile(fis, os);
}

From source file:bookkeepr.jettyhandlers.WebHandler.java

public void handle(String path, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    if (path.equals("/")) {
        response.sendRedirect("/web/");
    }//w ww.java  2s.c  o  m

    HttpClient httpclient = null;
    if (path.startsWith("/web/xmlify")) {
        ((Request) request).setHandled(true);
        if (request.getMethod().equals("POST")) {
            try {
                String remotePath = path.substring(11);

                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                XMLAble xmlable = null;
                try {
                    xmlable = httpForm2XmlAble(reader.readLine());
                } catch (BookKeeprException ex) {
                    response.sendError(400,
                            "Server could not form xml from the form data you submitted. " + ex.getMessage());
                    return;
                }
                if (xmlable == null) {
                    response.sendError(500,
                            "Server could not form xml from the form data you submitted. The server created a null value!");
                    return;

                }
                //                    XMLWriter.write(System.out, xmlable);
                //                    if(true)return;

                HttpPost httppost = new HttpPost(bookkeepr.getConfig().getExternalUrl() + remotePath);
                httppost.getParams().setBooleanParameter("http.protocol.strict-transfer-encoding", false);

                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                XMLWriter.write(out, xmlable);
                ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                httppost.setEntity(new InputStreamEntity(in, -1));
                Logger.getLogger(WebHandler.class.getName()).log(Level.INFO,
                        "Xmlifier posting to " + bookkeepr.getConfig().getExternalUrl() + remotePath);

                httpclient = bookkeepr.checkoutHttpClient();
                HttpResponse httpresp = httpclient.execute(httppost);
                for (Header head : httpresp.getAllHeaders()) {
                    if (head.getName().equalsIgnoreCase("transfer-encoding")) {
                        continue;
                    }
                    response.setHeader(head.getName(), head.getValue());
                }
                response.setStatus(httpresp.getStatusLine().getStatusCode());

                httpresp.getEntity().writeTo(response.getOutputStream());

            } catch (HttpException ex) {
                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING,
                        "HttpException " + ex.getMessage(), ex);
                response.sendError(500, ex.getMessage());

            } catch (URISyntaxException ex) {
                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
                response.sendError(400, "Invalid target URI");
            } finally {
                if (httpclient != null) {
                    bookkeepr.returnHttpClient(httpclient);
                }
            }

        }
        return;
    }

    if (request.getMethod().equals("GET")) {
        if (path.startsWith("/web")) {
            ((Request) request).setHandled(true);

            if (badchar.matcher(path).matches()) {
                response.sendError(400, "User Error");
                return;
            }
            String localpath = path.substring(4);
            Logger.getLogger(WebHandler.class.getName()).log(Level.FINE,
                    "Transmitting " + localroot + localpath);
            File targetFile = new File(localroot + localpath);
            if (targetFile.isDirectory()) {
                if (path.endsWith("/")) {
                    targetFile = new File(localroot + localpath + "index.html");
                } else {
                    response.sendRedirect(path + "/");
                    return;
                }
            }
            if (targetFile.exists()) {
                if (targetFile.getName().endsWith(".html") || targetFile.getName().endsWith(".xsl")) {
                    BufferedReader in = new BufferedReader(new FileReader(targetFile));
                    PrintStream out = null;
                    String hdr = request.getHeader("Accept-Encoding");
                    if (hdr != null && hdr.contains("gzip")) {
                        // if the host supports gzip encoding, gzip the output for quick transfer speed.
                        out = new PrintStream(new GZIPOutputStream(response.getOutputStream()));
                        response.setHeader("Content-Encoding", "gzip");
                    } else {
                        out = new PrintStream(response.getOutputStream());
                    }
                    String line = in.readLine();
                    while (line != null) {
                        if (line.trim().startsWith("%%%")) {
                            BufferedReader wrapper = new BufferedReader(
                                    new FileReader(localroot + "/wrap/" + line.trim().substring(3) + ".html"));
                            String line2 = wrapper.readLine();
                            while (line2 != null) {
                                out.println(line2);
                                line2 = wrapper.readLine();
                            }
                            wrapper.close();
                        } else if (line.trim().startsWith("***chooser")) {
                            String[] elems = line.trim().split("\\s");
                            try {
                                int type = TypeIdManager
                                        .getTypeFromClass(Class.forName("bookkeepr.xmlable." + elems[1]));
                                List<IdAble> items = this.bookkeepr.getMasterDatabaseManager()
                                        .getAllOfType(type);
                                out.printf("<select name='%sId'>\n", elems[1]);
                                for (IdAble item : items) {
                                    out.printf("<option value='%x'>%s</option>", item.getId(), item.toString());
                                }
                                out.println("</select>");

                            } catch (Exception e) {
                                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING,
                                        "Could not make a type ID for " + line.trim());
                            }
                        } else {

                            out.println(line);
                        }
                        line = in.readLine();
                    }
                    in.close();
                    out.close();
                } else {
                    outputToInput(new FileInputStream(targetFile), response.getOutputStream());
                }

            } else {
                response.sendError(HttpStatus.SC_NOT_FOUND);
            }
        }
    }
}

From source file:info.gewton.openid.servlet.OpenIDLoginServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SecurityContext sc = (SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
    OpenIDAuthenticationToken auth = (OpenIDAuthenticationToken) sc.getAuthentication();
    List<OpenIDAttribute> attributes = auth.getAttributes();
    for (OpenIDAttribute a : attributes) {
        if (a.getName().equals("namePerson")) {
            request.getSession().setAttribute("namePerson", a.getValues().get(0));
            break;
        }// w  w w.  j  a v  a 2s.c o m
    }
    response.sendRedirect(request.getContextPath() + "/index.jsp");
}

From source file:com.addthis.hydra.job.SpawnHttp.java

@Override
public void handle(String target, Request request, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    //To change body of implemented methods use File | Settings | File Templates.
    httpServletResponse.setCharacterEncoding(CharEncoding.UTF_8);
    if (target.equals("/")) {
        httpServletResponse.sendRedirect("/spawn/index.html");
    } else if (target.startsWith("/metrics")) {
        if (!metricsHandler.isStarted()) {
            log.warn("Metrics servlet failed to start");
        }/*w w w  .  j  a v  a  2s .  co m*/
        metricsHandler.handle(target, request, httpServletRequest, httpServletResponse);
    } else {
        HTTPService handler = serviceMap.get(target);
        if (handler != null) {
            try {
                HTTPLink link = new HTTPLink(target, request, httpServletResponse);
                if (failAuth(link))
                    return;
                handler.httpService(link);
            } catch (Exception ex) {
                log.warn("handler error " + ex, ex);
                httpServletResponse.sendError(500, ex.getMessage());
            }
        } else {
            File file = new File(webDir, target);
            if (file.exists() && file.isFile()) {
                OutputStream out = httpServletResponse.getOutputStream();
                InputStream in = new FileInputStream(file);
                byte buf[] = new byte[1024];
                int read = 0;
                while ((read = in.read(buf)) >= 0) {
                    out.write(buf, 0, read);
                }
            } else {
                log.warn("[http.unhandled] " + target);
                httpServletResponse.sendError(404);
            }
        }
    }
    ((Request) request).setHandled(true);
}

From source file:com.addthis.hydra.job.web.old.SpawnHttp.java

@Override
public void handle(String target, Request request, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    //To change body of implemented methods use File | Settings | File Templates.
    httpServletResponse.setCharacterEncoding(CharEncoding.UTF_8);
    if (target.equals("/")) {
        httpServletResponse.sendRedirect("/spawn/index.html");
    } else if (target.startsWith("/metrics")) {
        if (!metricsHandler.isStarted()) {
            log.warn("Metrics servlet failed to start");
        }/*from  w  w  w  . j a  va  2  s  .  c om*/
        metricsHandler.handle(target, request, httpServletRequest, httpServletResponse);
    } else {
        HTTPService handler = serviceMap.get(target);
        if (handler != null) {
            try {
                HTTPLink link = new HTTPLink(target, request, httpServletResponse);
                if (failAuth(link))
                    return;
                handler.httpService(link);
            } catch (Exception ex) {
                log.warn("handler error " + ex, ex);
                httpServletResponse.sendError(500, ex.getMessage());
            }
        } else {
            File file = new File(webDir, target);
            if (file.exists() && file.isFile()) {
                OutputStream out = httpServletResponse.getOutputStream();
                InputStream in = new FileInputStream(file);
                byte[] buf = new byte[1024];
                int read = 0;
                while ((read = in.read(buf)) >= 0) {
                    out.write(buf, 0, read);
                }
            } else {
                log.warn("[http.unhandled] " + target);
                httpServletResponse.sendError(404);
            }
        }
    }
    ((Request) request).setHandled(true);
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.AdminServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getQueryString() != null && request.getQueryString().length() > 0) {
        String target = doAction(request);
        response.sendRedirect(request.getContextPath() + request.getServletPath()
                + (request.getPathInfo() != null ? request.getPathInfo() : "")
                + (target != null ? ("#" + target) : ""));
        return;/*from   ww  w  .j  av  a 2 s.c om*/
    }

    Page page = new Page();
    page.title(getServletInfo());
    page.addHeader("");
    page.attribute("text", "#000000");
    page.attribute(Page.BGCOLOR, "#FFFFFF");
    page.attribute("link", "#606CC0");
    page.attribute("vlink", "#606CC0");
    page.attribute("alink", "#606CC0");

    page.add(new Block(Block.Bold).add(new Font(3, true).add(getServletInfo())));
    page.add(Break.rule);
    Form form = new Form(request.getContextPath() + request.getServletPath() + "?A=exit");
    form.method("GET");
    form.add(new Input(Input.Submit, "A", "Exit All Servers"));
    page.add(form);
    page.add(Break.rule);
    page.add(new Heading(3, "Components:"));

    List sList = new List(List.Ordered);
    page.add(sList);

    String id1;
    int i1 = 0;
    Iterator s = _servers.iterator();
    while (s.hasNext()) {
        id1 = "" + i1++;
        HttpServer server = (HttpServer) s.next();
        Composite sItem = sList.newItem();
        sItem.add("<B>HttpServer&nbsp;");
        sItem.add(lifeCycle(request, id1, server));
        sItem.add("</B>");
        sItem.add(Break.line);
        sItem.add("<B>Listeners:</B>");
        List lList = new List(List.Unordered);
        sItem.add(lList);

        HttpListener[] listeners = server.getListeners();
        for (int i2 = 0; i2 < listeners.length; i2++) {
            HttpListener listener = listeners[i2];
            String id2 = id1 + ":" + listener;
            lList.add(lifeCycle(request, id2, listener));
        }

        Map hostMap = server.getHostMap();

        sItem.add("<B>Contexts:</B>");
        List hcList = new List(List.Unordered);
        sItem.add(hcList);
        Iterator i2 = hostMap.entrySet().iterator();
        while (i2.hasNext()) {
            Map.Entry hEntry = (Map.Entry) (i2.next());
            String host = (String) hEntry.getKey();

            PathMap contexts = (PathMap) hEntry.getValue();
            Iterator i3 = contexts.entrySet().iterator();
            while (i3.hasNext()) {
                Map.Entry cEntry = (Map.Entry) (i3.next());
                String contextPath = (String) cEntry.getKey();
                java.util.List contextList = (java.util.List) cEntry.getValue();

                Composite hcItem = hcList.newItem();
                if (host != null)
                    hcItem.add("Host=" + host + ":");
                hcItem.add("ContextPath=" + contextPath);

                String id3 = id1 + ":" + host + ":"
                        + (contextPath.length() > 2 ? contextPath.substring(0, contextPath.length() - 2)
                                : contextPath);

                List cList = new List(List.Ordered);
                hcItem.add(cList);
                for (int i4 = 0; i4 < contextList.size(); i4++) {
                    String id4 = id3 + ":" + i4;
                    Composite cItem = cList.newItem();
                    HttpContext hc = (HttpContext) contextList.get(i4);
                    cItem.add(lifeCycle(request, id4, hc));
                    cItem.add("<BR>ResourceBase=" + hc.getResourceBase());
                    cItem.add("<BR>ClassPath=" + hc.getClassPath());

                    List hList = new List(List.Ordered);
                    cItem.add(hList);
                    int handlers = hc.getHandlers().length;
                    for (int i5 = 0; i5 < handlers; i5++) {
                        String id5 = id4 + ":" + i5;
                        HttpHandler handler = hc.getHandlers()[i5];
                        Composite hItem = hList.newItem();
                        hItem.add(lifeCycle(request, id5, handler, handler.getName()));
                        if (handler instanceof ServletHandler) {
                            hItem.add("<BR>" + ((ServletHandler) handler).getServletMap());
                        }
                    }
                }
            }
        }
        sItem.add("<P>");
    }

    response.setContentType("text/html");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache,no-store");
    Writer writer = response.getWriter();
    page.write(writer);
    writer.flush();
}

From source file:de.mpg.imeji.presentation.servlet.DigilibServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    String url = req.getParameter("id");
    String fn = req.getParameter("fn");
    if (url != null) {
        String path = internalStorageBase
                + url.replaceAll(navigation.getApplicationUrl() + FileServlet.SERVLET_PATH, "");
        path = path.replace("\\", "/");
        try {/*from  w  w w  .j  av  a 2 s. c  o  m*/
            resp.sendRedirect(req.getRequestURL().toString() + "?fn=" + path + "&dw=1000");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else if (fn != null) {
        SessionBean session = getSession(req);
        url = navigation.getApplicationUrl() + FileServlet.SERVLET_PATH + fn.replace(internalStorageBase, "");
        if (authorization.read(getUser(session), loadCollection(url, session))) {
            super.doGet(req, resp);
        } else {
            try {
                resp.sendError(403, "Security warning: You are not allowed to view this file.");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}