Example usage for javax.servlet.http HttpServletResponse sendError

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

Introduction

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

Prototype

public void sendError(int sc) throws IOException;

Source Link

Document

Sends an error response to the client using the specified status code and clears the buffer.

Usage

From source file:fr.aliasource.webmail.server.export.ExportConversationImpl.java

/**
 * The actual business logic./*w  w  w  .j  a  v a  2s.c  om*/
 * 
 * @param requ
 *            the request object
 * @param resp
 *            the response object
 * @throws IOException
 * @throws ServletException
 */
public void service(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
    logger.info("Export conversation called.");

    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String uri = req.getRequestURI();
    String convAndMessageIds = extractConversationIdFromRequestURI(uri);
    MessageId messageId = getMessageIdPart(convAndMessageIds);
    ConversationId conversationId = getConversationIdPart(convAndMessageIds);

    String folder = conversationId.getSourceFolder();

    logger.info("Conversation id: " + conversationId.getConversationId() + " folder: " + folder + " uri: " + uri
            + "Message id: " + messageId);

    Folder f = new Folder(folder, folder);
    ConversationReference cr = account.findConversation(conversationId);
    ClientMessage[] cm = null;
    if (messageId == null) {
        cm = account.fetchMessages(f, cr.getMessageIds());
    } else {
        cm = account.fetchMessages(f, Arrays.asList(messageId));
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ConversationExporter exporter = new ConversationExporter(
            req.getContextPath() + "/minig/images/logo_print.jpg");
    try {
        if (req.getRequestURI().endsWith(".html")) {
            exporter.exportToHtml(account, cr, cm, baos);
            response.setContentType("text/html");
        } else {
            exporter.exportToPdf(account, cr, cm, baos);
            response.setContentType("application/pdf");
        }
    } catch (ConversationExporterException e) {
        logger.error("Cannot render conversation", e);
        throw new ServletException(e);
    }

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");

    response.setContentLength(baos.size());
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();

}

From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from w  w w .  ja v a 2  s.  c om
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(Base64.getDecoder().decode(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:cn.shengyuan.yun.admin.system.controller.CommonController.java

/**
 * ??/*ww w.j  av  a 2s  .  co m*/
 */
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "unauthorized");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    return "/common/unauthorized";
}

From source file:com.evolveum.midpoint.gui.impl.util.ReportPeerQueryInterceptor.java

private boolean isFileAndExists(File reportFile, String fileName, HttpServletResponse response,
        String operation) throws IOException {

    if (!reportFile.exists()) {
        LOGGER.warn(operation + " not successful. The file: {} was not found on the filesystem.", fileName);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return false;
    }/*from  w w  w. j  a  v a2s  . c om*/

    if (reportFile.isDirectory()) {
        LOGGER.warn(operation
                + " not successful. The file is actually a directory with the name: {}. This operation is prohibited.",
                fileName);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }

    return true;

}

From source file:nl.tue.gale.ae.LoginServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    LoginManager login = (LoginManager) getApplicationContext().getBean("loginManager");
    ProcessorManager pm = (ProcessorManager) getApplicationContext().getBean("processorManager");
    login.doLoginPage(pm.createResource(req, resp));
    if (!resp.isCommitted())
        resp.sendError(501);
}

From source file:com.logiclander.jaasmine.authentication.http.SimpleLogoutServlet.java

/**
 * Logs out the Subject associated with the user.
 *
 * After the logout is done, the request is dispatched to a Servlet or JSP
 * specified by the {@code postLogoutProcessorName} init-param.  If the
 * param was not specified, a {@code text/plain} message will be written
 * to the response.//  w w w  .  jav a  2  s  .  c om
 *
 * This method is not idempotent.  If a request is made successfully once,
 * the user will be logged out.  Subsequent requests without a login will
 * cause an HTTP 403 - Forbidden to be returned.
 *
 * @param req the HttpServletRequest
 * @param resp the HttpServletResponse
 * @throws ServletException if a ServletException is thrown after the
 * request is dispatched to the post logout processor.
 * @throws IOException if an I/O error occurs.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession sess = req.getSession();
    Subject subj = (Subject) sess.getAttribute(AuthenticationService.SUBJECT_KEY);

    if (subj == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Log out the Subject
    AuthenticationService as = new SimpleAuthenticationService(appName);
    as.logout(subj);

    // Invalidate the session
    sess.invalidate();

    resp.setStatus(HttpServletResponse.SC_OK);
    RequestDispatcher rd = getServletContext().getNamedDispatcher(postLogoutProcessorName);

    if (rd != null) {
        resp.setContentType("text/html");
        rd.include(req, resp);
    } else {
        sendPlainTextResponse(resp);
    }

}

From source file:com.haulmont.cuba.core.controllers.FileDownloadController.java

protected UserSession getSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UUID sessionId;// www .  j a  va  2s  . com
    try {
        sessionId = UUID.fromString(request.getParameter("s"));
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    UserSession session = userSessions.getAndRefresh(sessionId);
    if (session == null)
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return session;
}

From source file:com.cueup.hegemon.testing.server.HegemonTestServer.java

/**
 *  The request handler translates an HTTP request to a test class and method to run.
 *//*from   w  w  w  .  ja v a 2  s.  c  o  m*/
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    if ("/favicon.ico".equals(target)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        baseRequest.setHandled(true);
        return;
    }

    if (target.length() <= 1) {
        String[] names = AllClassesList.TEST_CLASS_NAMES
                .toArray(new String[AllClassesList.TEST_CLASS_NAMES.size()]);
        Arrays.sort(names);
        markHandled(baseRequest, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "text/html");
        for (String name : names) {
            response.getWriter().println("<p><a href=\"" + name + "\">" + name + "</a></p>");
        }
        return;
    }

    try {
        Class c = loadClassByReference(target.substring(1));
        if (c == null) {
            markHandled(baseRequest, response, HttpServletResponse.SC_NOT_FOUND, "text/plain");
            response.getWriter()
                    .println("Could not find class with name or reference to " + target.substring(1));
            return;
        }

        HegemonRunner runner = new HegemonRunner(c, baseRequest.getQueryString(), this.loadPath);
        RunNotifier notifier = new RunNotifier();
        notifier.addListener(new ResponseListener(response, createCustomTestOutputHandler()));

        startTestClass();
        long start = System.currentTimeMillis();

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(
                "<style>.ok {color:green} .fail {color:red} .ignore {color:orange} pre {margin-left: 24px}</style>");
        runner.run(notifier);
        response.setStatus(HttpServletResponse.SC_OK);

        response.getWriter()
                .println("<br>Finished in " + ((System.currentTimeMillis() - start) / 1000.0) + " seconds.");

        baseRequest.setHandled(true);

    } catch (Throwable t) { // lint: disable=IllegalCatchCheck
        markHandled(baseRequest, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "text/plain");
        t.printStackTrace(response.getWriter());
    }

}

From source file:net.shopxx.controller.admin.CommonController.java

/**
 * ??/*from  w  ww.  j  a  v a2s  . co m*/
 */
@RequestMapping("/admin/common/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "unauthorized");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    return "/admin/common/unauthorized";
}

From source file:com.haulmont.cuba.core.controllers.FileDownloadController.java

protected FileDescriptor getFileDescriptor(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    UUID fileId;//  w ww. ja  v a2  s . c  om
    try {
        fileId = UUID.fromString(request.getParameter("f"));
    } catch (Exception e) {
        log.error("Error parsing fileId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    FileDescriptor fileDescriptor = dataService.load(new LoadContext<>(FileDescriptor.class).setId(fileId));
    if (fileDescriptor == null)
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return fileDescriptor;
}