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.thinkberg.webdav.PutHandler.java

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

    try {/*from  ww  w . j  av a2 s  . c o m*/
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        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();
    long bytesCopied = Util.copyStream(is, os);
    String contentLengthHeader = request.getHeader("Content-length");
    LOG.debug(String.format("sent %d/%s bytes", bytesCopied,
            contentLengthHeader == null ? "unknown" : contentLengthHeader));
    os.flush();
    object.close();

    response.setStatus(HttpServletResponse.SC_CREATED);
}

From source file:com.mirth.connect.server.servlets.ChannelStatusServlet.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.  java2  s.c  o  m
        try {
            ChannelStatusController channelStatusController = ControllerFactory.getFactory()
                    .createChannelStatusController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String channelId = request.getParameter("id");
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            parameterMap.put("channelId", channelId);

            if (operation.equals(Operations.CHANNEL_START)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.startChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_STOP)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.stopChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_PAUSE)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.pauseChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_RESUME)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.resumeChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_GET_STATUS)) {
                response.setContentType(APPLICATION_XML);
                List<ChannelStatus> channelStatuses = null;

                if (!isUserAuthorized(request, null)) {
                    channelStatuses = new ArrayList<ChannelStatus>();
                } else if (doesUserHaveChannelRestrictions(request)) {
                    channelStatuses = redactChannelStatuses(request,
                            channelStatusController.getChannelStatusList());
                } else {
                    channelStatuses = channelStatusController.getChannelStatusList();
                }

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

From source file:org.geoserver.ows.AbstractURLPublisher.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    URL url = getUrl(request);//from  www.j a  v  a  2s. c o  m

    // if not found return a 404
    if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    File file = DataUtilities.urlToFile(url);
    if (file != null && file.exists() && file.isDirectory()) {
        String uri = request.getRequestURI().toString();
        uri += uri.endsWith("/") ? "index.html" : "/index.html";

        response.addHeader("Location", uri);
        response.sendError(HttpServletResponse.SC_MOVED_TEMPORARILY);

        return null;
    }

    // set the mime if known by the servlet container, set nothing otherwise
    // (Tomcat behaves like this when it does not recognize the file format)
    String mime = getServletContext().getMimeType(new File(url.getFile()).getName());
    if (mime != null) {
        response.setContentType(mime);
    }

    // set the content length and content type
    URLConnection connection = null;
    InputStream input = null;
    try {
        connection = url.openConnection();
        long length = connection.getContentLength();
        if (length > 0 && length <= Integer.MAX_VALUE) {
            response.setContentLength((int) length);
        }

        long lastModified = connection.getLastModified();
        if (lastModified > 0) {
            SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.ENGLISH);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String formatted = format.format(new Date(lastModified)) + " GMT";
            response.setHeader("Last-Modified", formatted);
        }

        // Guessing the charset (and closing the stream)
        EncodingInfo encInfo = null;
        OutputStream output = null;
        final byte[] b4 = new byte[4];
        int count = 0;
        // open the output
        input = connection.getInputStream();

        // Read the first four bytes, and determine charset encoding
        count = input.read(b4);
        encInfo = XmlCharsetDetector.getEncodingName(b4, count);
        response.setCharacterEncoding(encInfo.getEncoding() != null ? encInfo.getEncoding() : "UTF-8");

        // send out the first four bytes read
        output = response.getOutputStream();
        output.write(b4, 0, count);

        // copy the content to the output
        byte[] buffer = new byte[8192];
        int n = -1;
        while ((n = input.read(buffer)) != -1) {
            output.write(buffer, 0, n);
        }
    } finally {
        if (input != null)
            input.close();
    }

    return null;
}

From source file:edu.internet2.middleware.shibboleth.idp.StatusServlet.java

/** {@inheritDoc} */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isAuthenticated(request)) {
        response.sendError(HttpStatus.SC_UNAUTHORIZED);
        return;/*from   w  w w  . j  a v a  2s.c  o  m*/
    }

    response.setContentType("text/plain");
    PrintWriter output = response.getWriter();

    printOperatingEnvironmentInformation(output);
    output.println();
    printIdPInformation(output);
    output.println();
    printRelyingPartyConfigurationsInformation(output, request.getParameter("relyingParty"));

    output.flush();
}

From source file:org.magnum.mobilecloud.video.VideoServiceCtrl.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)//  w  w w  . ja va 2  s .  co m
public @ResponseBody void likeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal user)
        throws IOException {

    if (!videos.exists(id)) {
        response.sendError(404);
        return;
    }
    String username = user.getName();
    Video v = videos.findOne(id);
    Set<String> likesUsernames = v.getLikesUsernames();
    List<String> happyUsers = v.getLikedVideo();
    // Checks if the user has already liked the video.
    if (likesUsernames.contains(username)) {
        response.sendError(400);
        return;
    } else {
        long likes = v.getLikes();
        v.setLikes(++likes);
        v.getLikesUsernames().add(username);
    }
    if (!happyUsers.contains(username)) {
        happyUsers.add(username);
        v.setLikedVideo(happyUsers);
    }
    videos.save(v);
}

From source file:org.magnum.mobilecloud.video.VideoServiceCtrl.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)//from   ww  w  . j  a  v a 2 s.c o  m
public @ResponseBody void unlikeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal user)
        throws IOException {

    if (!videos.exists(id)) {
        response.sendError(404);
        return;
    }
    String username = user.getName();
    Video v = videos.findOne(id);
    Set<String> unlikesUsernames = v.getUnlikesUsernames();
    List<String> happyUsers = v.getLikedVideo();
    // Checks if the user has already liked the video.
    if (unlikesUsernames.contains(username)) {
        response.sendError(400);
        return;
    } else {
        long likes = v.getLikes();
        v.setLikes(--likes);
        v.getUnlikesUsernames().add(username);
    }
    if (happyUsers.contains(username)) {
        happyUsers.remove(username);
        v.setLikedVideo(happyUsers);
    }
    videos.save(v);
}

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

protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException {
    UUID sessionUUID;//from   www .  j ava2  s. c  o m
    try {
        sessionUUID = UUID.fromString(sessionId);
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    UserSession session = userSessions.getAndRefresh(sessionUUID);
    if (session == null)
        response.sendError(HttpServletResponse.SC_FORBIDDEN);

    return session;
}

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

private UserSession getSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UUID sessionId;//from   www .  j a v  a  2 s.  co  m
    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.sesnu.orion.web.controller.PaymentController.java

@RequestMapping(value = "/api/user/pay", method = RequestMethod.PUT)
public @ResponseBody List<PayView> updateItem(HttpServletResponse response, @RequestBody Payment pay)
        throws Exception {

    if (payDao.get(pay.getId()) == null) {
        response.sendError(400);
        return null;
    }/*from   w  w  w  .  j a v a2  s .com*/

    if (pay.getStatus().equals("Approved")) {
        response.sendError(400, Util.parseError("Payment is approved, it can not be deleted"));
        return null;
    }

    pay.setUpdatedOn(Util.parseDate(new Date(), "/"));
    payDao.saveOrUpdate(pay);

    List<PayView> Payments = payDao.listByOrderRef(pay.getOrderRef());
    if (Payments.size() > 0) {
        return Payments;
    }
    response.sendError(404);
    return null;

}

From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java

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

    response.sendError(response.SC_NOT_FOUND);
}