Example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

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

Introduction

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

Prototype

int SC_INTERNAL_SERVER_ERROR

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

Click Source Link

Document

Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.

Usage

From source file:com.linuxbox.enkive.web.search.DeleteSearchWebScript.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String searchIds = "";
    ArrayList<String> failedDeletedSearches = new ArrayList<String>();
    searchIds = WebScriptUtils.cleanGetParameter(req, "searchids");
    WorkspaceService workspaceService = getWorkspaceService();
    Workspace workspace;//from  ww  w . j  av a2  s  .  c o m

    try {
        workspace = workspaceService.getActiveWorkspace(req.getUserPrincipal().getName());

        for (String searchId : searchIds.split(",")) {
            if (!searchId.isEmpty()) {
                try {
                    workspace.deleteSearchResult(searchIds);

                    SearchResult result = workspace.getSearchResultBuilder().getSearchResult(searchId);
                    result.deleteSearchResult();
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("deleted search at id " + searchId);
                } catch (WorkspaceException e) {
                    failedDeletedSearches.add(searchId);
                }
            }
        }
        workspace.saveWorkspace();
        if (!failedDeletedSearches.isEmpty()) {
            respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
            throw new IOException("Could not delete searches with UUIDs " + failedDeletedSearches.toString());
        }
    } catch (WorkspaceException e1) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new IOException("Could not update workspace to remove searches");
    }
}

From source file:org.logger.event.web.spring.exception.EventExceptionResolver.java

@Override
public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/*from   w w w. j  a  va2  s  .c  om*/
    ErrorObject errorObject = null;
    ex.printStackTrace();
    logger.error("Error in Resolver : {}", ex);
    if (ex instanceof AccessDeniedException) {
        errorObject = new ErrorObject(403, ex.getMessage());
        response.setStatus(403);
    } else if (ex instanceof SizeLimitExceededException) {
        response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        errorObject = new ErrorObject(413, ex.getMessage());
    } else if (ex instanceof S3ServiceException) {
        response.setStatus(500);
        errorObject = new ErrorObject(500, ((S3ServiceException) ex).getErrorMessage());
    } else {
        errorObject = new ErrorObject(500, ex.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    ModelAndView jsonModel = new ModelAndView("rest/model");
    jsonModel.addObject("model", new JSONSerializer().exclude("*.class").serialize(errorObject));
    return jsonModel;
}

From source file:de.afbb.bibo.servlet.server.servlet.MainServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w  w .j av  a2s .c  o m
 *
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws NumberFormatException
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 * @throws java.lang.InterruptedException
 * @throws org.apache.commons.fileupload.FileUploadException
 */
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws NumberFormatException, IOException {
    boolean valid = true;
    final String requestRoot = Utils.getRequestPart(request, 0);
    log.debug("entering MAIN Servlet...");

    if (!requestRoot.equals("/login")) {
        valid = SessionContainer.getInstance().validate(request.getHeader("sessionId"));
    }
    log.info("new request: " + request.getRequestURI());
    if (!valid) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {

        response.setContentType("application/json");

        try {
            switch (requestRoot) {
            case "/login":
                new LoginServlet(request, response).processRequest();
                break;
            case "/user":
                new UserServlet(request, response).processRequest();
                break;
            case "/stock":
                new StockServlet(request, response).processRequest();
                break;
            case "/borrow":
                new BorrowServlet(request, response).processRequest();
                break;
            default:
                Utils.returnErrorMessage(MainServlet.class, request, response);
                break;
            }
        } catch (final SQLException | IOException e) {
            log.debug(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.ikon.servlet.WorkflowRegisterServlet.java

/**
 * Handle GET and POST//w w  w  .  ja  va  2  s.com
 */
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("service({}, {}", request, response);
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    try {
        String user = PrincipalUtils.getUser();

        if (Config.ADMIN_USER.equals(user)) {
            String msg = handleRequest(request);
            log.info("Status: {}", msg);
            out.print(msg);
            out.flush();
        } else {
            log.warn("Workflow should be registered by {}", Config.ADMIN_USER);
        }
    } catch (FileUploadException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "FileUploadException: " + e.getMessage());
    } catch (IOException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "IOException: " + e.getMessage());
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:es.eucm.mokap.backend.server.MokapBackend.java

/**
 * Method: POST Processes post requests.
 * //  w  w w  .  j ava  2 s  . c  o  m
 * <pre>
 * - Requests must be multipart/form-data.
 * - The field with the file must be named "file". 
 * - The file must be a .zip compressed file with the structure
 *   defined in {@link UploadZipStructure}.
 * </pre>
 */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    MokapInsertController iCont = new MokapInsertController();
    // Check api key
    if (!ApiKeyVerifier.checkApiKey(req, resp)) {
        return;
    } else {

        try {
            // Get the uploaded file stream
            FileItemStream fis = getUploadedFile(req);
            if (fis != null) {
                // Actually process the uploaded resource
                String str = iCont.processUploadedResource(fis);
                // Send the response
                PrintWriter out = resp.getWriter();
                out.print(str);
                out.flush();
                out.close();
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        ServerReturnMessages.INVALID_UPLOAD_FILENOTFOUND);
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    ServerReturnMessages.m(ServerReturnMessages.GENERIC_INTERNAL_ERROR, e.getMessage()));
        }
    }
}

From source file:com.adito.setup.actions.SessionInformationAction.java

public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {/*from w w w  . j a va  2 s  . c  om*/
        PolicyUtil.checkPermission(PolicyConstants.STATUS_TYPE_RESOURCE_TYPE, PolicyConstants.PERM_VIEW,
                request);
        String ticket = request.getParameter("ticket");
        if (ticket == null) {
            throw new Exception("No ticket parameter supplied.");
        }
        SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(ticket);
        request.setAttribute(Constants.REQ_ATTR_INFO_RESOURCE, info);
        return sessionInformation(mapping, form, request, response);
    } catch (Exception e) {
        log.error("Failed to get session information. ", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
    return null;
}

From source file:dk.hlyh.hudson.plugins.mavenrepo.repo.ChecksumFile.java

@Override
public void sendResponse(StaplerRequest req, StaplerResponse rsp) throws IOException {
    FileInputStream fis = new FileInputStream(filename);
    try {//from  w  w  w .  j av  a 2  s .  c om
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        messageDigest.reset();

        // Stream the file contents to the MessageDigest.
        byte[] buffer = new byte[STREAMING_BUFFER_SIZE];
        int size = fis.read(buffer, 0, STREAMING_BUFFER_SIZE);
        while (size >= 0) {
            messageDigest.update(buffer, 0, size);
            size = fis.read(buffer, 0, STREAMING_BUFFER_SIZE);
        }

        Hex encoder = new Hex();
        byte[] encodeded = encoder.encode(messageDigest.digest());

        rsp.setContentType("text/plain");
        rsp.getOutputStream().write(encodeded);

    } catch (NoSuchAlgorithmException ex) {
        log.warn("Could not generate '" + algorithm + "' checksum for: " + filename, ex);
        rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        try {
            fis.close();
        } catch (IOException e) {
            /* ignored */
        }
    }
}

From source file:com.swingtech.apps.filemgmt.controller.StreamingViewRenderer.java

@Override
protected void renderMergedOutputModel(Map objectMap, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    InputStream dataStream = (InputStream) objectMap.get(DownloadConstants.INPUT_STREAM);

    if (dataStream == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from  w  w w  .  ja  v  a 2  s.  com*/
    }
    long length = (Long) objectMap.get(DownloadConstants.CONTENT_LENGTH);
    String fileName = (String) objectMap.get(DownloadConstants.FILENAME);
    Date lastModifiedObj = (Date) objectMap.get(DownloadConstants.LAST_MODIFIED);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = lastModifiedObj.getTime();
    String contentType = (String) objectMap.get(DownloadConstants.CONTENT_TYPE);

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
            // in
            // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                // IAE
                // if
                // invalid.
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = StringUtils.sublong(part, 0, part.indexOf("-"));
                long end = StringUtils.sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                    // in
                    // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If
        // content type is supported by
        // the browser, then set to inline, else attachment which will pop a
        // 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            copy(input, output, length, r.start, r.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println
            // methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }

}

From source file:com.epam.aem.training.core.servlets.RotatetdImageServlet.java

@Override
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp)
        throws ServletException, IOException {

    Image image = this.resolveImage(req);
    if (image == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;// w ww.  ja  va2 s .  c o  m
    }
    if (!image.hasContent()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // get pure layer
    Layer layer = this.getLayer(image);
    if (layer == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    //rotating layer
    this.imageRotator.rotateUpDown(layer);
    try {
        final String mimeType = image.getMimeType();
        layer.write(mimeType, 1, resp.getOutputStream());
    } catch (RepositoryException ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    resp.flushBuffer();
}

From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Error: Request type not supported.");
        return;/* w ww . j a va2s  .  c om*/
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> items = upload.parseRequest(req);

        String depositurl = null;

        for (FileItem item : items) {
            if (item.getFieldName() != null && item.getFieldName().equals("depositurl")) {
                depositurl = item.getString();
            }
        }

        if (depositurl == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required paremeter: depositurl");
            return;
        }

        for (FileItem item : items) {
            String name = item.getName();

            if (item.isFormField() || name == null || name.isEmpty()) {
                continue;
            }

            uploadfile(depositurl, name, item.getInputStream(), resp);
        }
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    } catch (FileUploadException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    }
}