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:com.nabla.dc.server.ImageService.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final String imageId = request.getParameter("id");
    if (imageId == null || imageId.isEmpty()) {
        if (log.isTraceEnabled())
            log.trace("missing image ID");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {/*from   w  ww  . j  a v a2  s.  com*/
        try {
            if (exportImage(imageId, response)) {
                //   response.setStatus(HttpServletResponse.SC_OK);
            } else
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (final SQLException e) {
            if (log.isErrorEnabled())
                log.error("SQL error " + e.getErrorCode() + "-" + e.getSQLState(), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (final Throwable e) {
            if (log.isErrorEnabled())
                log.error("unexpected error", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java

private boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String auth = request.getHeader("authorization");
    if (auth == null) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"PID Cache\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } else {/*from  ww  w .ja  v  a 2  s.  c om*/
        auth = auth.substring(6);
        String cred = new String(Base64.decodeBase64(auth.getBytes()));
        if (cred.contains(":")) {

            String[] userPass = cred.split(":");
            String userName = PropertyReader.getProperty("escidoc.pidcache.user.name");
            String password = PropertyReader.getProperty("escidoc.pidcache.user.password");

            if (!userPass[0].equals(userName) || !userPass[1].equals(password)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            } else {
                return true;
            }
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    }
}

From source file:com.mirth.connect.server.servlets.ChannelServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {//  w  w  w  .  jav a2  s . co  m
        try {
            ChannelController channelController = ControllerFactory.getFactory().createChannelController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            ServerEventContext context = new ServerEventContext();
            context.setUserId(getCurrentUserId(request));

            if (operation.equals(Operations.CHANNEL_GET)) {
                response.setContentType(APPLICATION_XML);
                List<Channel> channels = null;
                Channel channel = (Channel) serializer.fromXML(request.getParameter("channel"));
                parameterMap.put("channel", channel);

                if (!isUserAuthorized(request, parameterMap)) {
                    channels = new ArrayList<Channel>();
                } else if (doesUserHaveChannelRestrictions(request)) {
                    channels = redactChannels(request, channelController.getChannel(channel));
                } else {
                    channels = channelController.getChannel(channel);
                }

                serializer.toXML(channels, out);
            } else if (operation.equals(Operations.CHANNEL_UPDATE)) {
                Channel channel = (Channel) serializer.fromXML(request.getParameter("channel"));
                boolean override = Boolean.valueOf(request.getParameter("override")).booleanValue();
                parameterMap.put("channel", channel);
                parameterMap.put("override", override);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    // NOTE: This needs to be print rather than println to
                    // avoid the newline
                    out.print(channelController.updateChannel(channel, context, override));
                }
            } else if (operation.equals(Operations.CHANNEL_REMOVE)) {
                Channel channel = (Channel) serializer.fromXML(request.getParameter("channel"));
                parameterMap.put("channel", channel);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelController.removeChannel(channel, context);
                }
            } else if (operation.equals(Operations.CHANNEL_GET_SUMMARY)) {
                response.setContentType(APPLICATION_XML);
                List<ChannelSummary> channelSummaries = null;
                Map<String, Integer> cachedChannels = (Map<String, Integer>) serializer
                        .fromXML(request.getParameter("cachedChannels"));
                parameterMap.put("cachedChannels", cachedChannels);

                if (!isUserAuthorized(request, parameterMap)) {
                    channelSummaries = new ArrayList<ChannelSummary>();
                } else if (doesUserHaveChannelRestrictions(request)) {
                    channelSummaries = redactChannelSummaries(request,
                            channelController.getChannelSummary(cachedChannels));
                } else {
                    channelSummaries = channelController.getChannelSummary(cachedChannels);
                }

                serializer.toXML(channelSummaries, out);
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:com.adito.core.MessageResourceLoaderServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String name = request.getPathInfo().substring(1);
    if (name.equals("")) {
        log.error("No name supplied to the class loader servlet.");
        response.sendError(500);
        return;//from   w  w w.  ja v  a 2  s.co  m
    }
    int idx = name.lastIndexOf('/');
    String basename = name;
    if (idx != -1) {
        basename = name.substring(idx + 1);
    }
    if (!basename.startsWith("ApplicationResources")
            || (!basename.endsWith(".properties") && !basename.endsWith(".class"))) {
        log.debug("Attempt to load something other that a resource bundle via the class loader servlet.");
        response.sendError(500);
        return;
    }

    /* This is a hack to get around the problem where we never get
     * get a request for the default language resources when they are
     * in a properties file. This is because we use a class loader on
     * the client end to retrieve the resources.
     */

    if (basename.endsWith(".class")) {
        basename = basename.substring(0, basename.length() - 6) + ".properties";
        name = name.substring(0, name.length() - 6) + ".properties";
    }

    /*
     * Load into byte array so we get the content length before sending on
     * to the client
     */
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    InputStream in = ContextHolder.getContext().getContextLoader().getResourceAsStream(name);
    if (in == null) {
        response.setContentType("text/plain");
        response.sendError(404, "Class not found");
    } else {
        try {
            Util.copy(in, bout);
        } finally {
            bout.close();
            in.close();
        }
        response.setContentType("text/plain");
        response.setContentLength(bout.size());
        response.setStatus(200);
        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        sendFile(bin, bout.size(), response);
    }
}

From source file:org.pegadi.webapp.view.FileView.java

protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // get the file from the map
    File file = (File) map.get("file");

    // check if it exists
    if (file == null || !file.exists() || !file.canRead()) {
        log.warn("Error reading: " + file);
        try {//from  ww  w. j  ava2s .  co m
            response.sendError(404);
        } catch (IOException e) {
            log.error("Could not write to response", e);
        }
        return;
    }
    // give some info in the response
    response.setContentType(getServletContext().getMimeType(file.getAbsolutePath()));
    // files does not change so often, allow three days caching
    response.setHeader("Cache-Control", "max-age=259200");
    response.setContentLength((int) file.length());

    // start writing to the response
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
        out = new BufferedOutputStream(response.getOutputStream());
        in = new BufferedInputStream(new FileInputStream(file));
        int c = in.read();
        while (c != -1) {
            out.write(c);
            c = in.read();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:com.thinkberg.moxo.dav.PutHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {/*from w  w  w.j a  va2  s .  c  o m*/
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    // it is forbidden to write data on a folder
    if (object.exists() && FileType.FOLDER.equals(object.getType())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    FileObject parent = object.getParent();
    if (!parent.exists()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (!FileType.FOLDER.equals(parent.getType())) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    InputStream is = request.getInputStream();
    OutputStream os = object.getContent().getOutputStream();
    log("PUT sends " + request.getHeader("Content-length") + " bytes");
    log("PUT copied " + Util.copyStream(is, os) + " bytes");
    os.flush();
    object.close();

    response.setStatus(HttpServletResponse.SC_CREATED);
}

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

/**
 * ??// ww  w  .j  av  a  2s. c  o 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 "/admin/common/unauthorized";
}

From source file:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // check, if we are doing the right request
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//w  w  w  .j  av  a  2s  .com
    }

    // create the disk file factory, limiting the file size to 20 MB
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB
    fileItemFactory.setRepository(tmpDir);

    String filename = null;

    // parse the request
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator();

        // go over the form fields and look for our file
        while (itr.hasNext()) {
            FileItem item = itr.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equals("upload_jar_file")) {

                    // found the file, store it to the specified location
                    filename = item.getName();
                    File file = new File(destinationDir, filename);
                    item.write(file);
                    break;
                }
            }
        }
    } catch (FileUploadException ex) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload.");
        return;
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An unknown error occurred during the file upload.");
        return;
    }

    // write the okay message
    resp.sendRedirect(targetPage);
}

From source file:com.nabla.wapp.server.basic.general.ExportService.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final String id = request.getParameter("id");
    if (id == null || id.isEmpty()) {
        if (log.isTraceEnabled())
            log.trace("missing file ID");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;//from   w  ww  .  j a v  a2 s. c o  m
    }
    final UserSession userSession = UserSession.load(request);
    if (userSession == null) {
        if (log.isTraceEnabled())
            log.trace("missing user session");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    try {
        if (exportFile(id, userSession, response)) {
            //   response.setStatus(HttpServletResponse.SC_OK);
        } else
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (final SQLException e) {
        if (log.isErrorEnabled())
            log.error("SQL error " + e.getErrorCode() + "-" + e.getSQLState(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (final Throwable e) {
        if (log.isErrorEnabled())
            log.error("unexpected error", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.mirth.connect.server.servlets.EventServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {//from ww w .  java 2  s  . c om
        try {
            EventController eventController = ControllerFactory.getFactory().createEventController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String uid = null;
            boolean useNewTempTable = false;
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (StringUtils.isNotBlank(request.getParameter("uid"))) {
                uid = request.getParameter("uid");
                useNewTempTable = true;
            } else {
                uid = request.getSession().getId();
            }

            if (operation.equals(Operations.EVENT_CREATE_TEMP_TABLE)) {
                EventFilter eventFilter = (EventFilter) serializer.fromXML(request.getParameter("filter"));
                parameterMap.put("filter", eventFilter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    out.println(eventController.createTempTable(eventFilter, uid, useNewTempTable));
                }
            } else if (operation.equals(Operations.EVENT_REMOVE_FILTER_TABLES)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    eventController.removeFilterTable(uid);
                }
            } else if (operation.equals(Operations.EVENT_GET_BY_PAGE)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    int page = Integer.parseInt(request.getParameter("page"));
                    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
                    int max = Integer.parseInt(request.getParameter("maxEvents"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(eventController.getEventsByPage(page, pageSize, max, uid), out);
                }
            } else if (operation.equals(Operations.EVENT_GET_BY_PAGE_LIMIT)) {
                EventFilter eventFilter = (EventFilter) serializer.fromXML(request.getParameter("filter"));
                parameterMap.put("filter", eventFilter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    int page = Integer.parseInt(request.getParameter("page"));
                    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
                    int max = Integer.parseInt(request.getParameter("maxEvents"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(
                            eventController.getEventsByPageLimit(page, pageSize, max, uid, eventFilter), out);
                }
            } else if (operation.equals(Operations.EVENT_REMOVE_ALL)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    eventController.removeAllEvents();

                    // Audit after removal
                    isUserAuthorized(request, null);
                }
            } else if (operation.equals(Operations.EVENT_EXPORT_ALL)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    out.println(eventController.exportAllEvents());
                }
            } else if (operation.equals(Operations.EVENT_EXPORT_AND_REMOVE_ALL)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);

                    // Add file path of export and audit after removal
                    String exportPath = eventController.exportAndRemoveAllEvents();
                    parameterMap.put("file", exportPath);
                    isUserAuthorized(request, parameterMap);

                    out.println(exportPath);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}