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:net.cbtltd.server.UploadFileService.java

/**
 * Handles upload file requests is in a page submitted by a HTTP POST method.
 * Form field values are extracted into a parameter list to set an associated Text instance.
 * 'File' type merely saves file and creates associated db record having code = file name.
 * Files may be rendered by reference in a browser if the browser is capable of the file type.
 * 'Image' type creates and saves thumbnail and full size jpg images and creates associated
 * text record having code = full size file name. The images may be viewed by reference in a browser.
 * 'Blob' type saves file and creates associated text instance having code = full size file name
 * and a byte array data value equal to the binary contents of the file.
 *
 * @param request the HTTP upload request.
 * @param response the HTTP response.//from   w w  w  .j a  va 2 s .c  o  m
 * @throws ServletException signals that an HTTP exception has occurred.
 * @throws IOException signals that an I/O exception has occurred.
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletRequestContext ctx = new ServletRequestContext(request);

    if (ServletFileUpload.isMultipartContent(ctx) == false) {
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The servlet can only handle multipart requests."));
        return;
    }

    LOG.debug("UploadFileService doPost request " + request);

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

    LOG.debug("\n doPost upload " + upload);

    SqlSession sqlSession = RazorServer.openSession();
    try {
        HashMap<String, String> params = new HashMap<String, String>();
        for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
            if (item.isFormField()) { // add for field value to parameter list
                String param = item.getFieldName();
                String value = item.getString();
                params.put(param, value);
            } else if (item.getSize() > 0) { // process uploaded file
                //               String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName();    // input file path
                String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path
                LOG.debug("doPost fn " + fn);
                byte[] data = item.get();
                String mimeType = item.getContentType();

                String productId = item.getFieldName();
                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(productId);
                while (m.find()) {
                    productId = m.group();
                    LOG.debug("Image uploaded for Product ID: " + productId);
                    break;
                }

                // TO DO - convert content type to mime..also check if uploaded type is image

                // getMagicMatch accepts Files or byte[],
                // which is nice if you want to test streams
                MagicMatch match = null;
                try {
                    match = parser.getMagicMatch(data, false);
                    LOG.debug("Mime type of image: " + match.getMimeType());
                } catch (MagicParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicMatchNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (match != null) {
                    mimeType = match.getMimeType();
                }

                // image processor logic needs to know about the format of the image
                String contentType = RazorConfig.getMimeExtension(mimeType);

                if (StringUtils.isNotEmpty(contentType)) {
                    ImageService.uploadImages(sqlSession, productId, item.getFieldName(),
                            params.get(Text.FILE_NOTES), data, contentType);
                    LOG.debug("doPost commit params " + params);
                    sqlSession.commit();
                } else {
                    // unknown content/mime type...do not upload the file
                    sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST,
                            "File type - " + contentType + " is not supported"));
                }
                //               File file = new File(fn);                            // output file name
                //               File tempf = File.createTempFile(Text.TEMP_FILE, "");
                //               item.write(tempf);
                //               file.delete();
                //               tempf.renameTo(file);
                //               int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS));
                //               if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;}
                //               int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS));
                //               if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;}
                //
                //               setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels);
            }
        }
        sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK"));
    } catch (Throwable x) {
        sqlSession.rollback();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage()));
        LOG.error("doPost error " + x.getMessage());
    } finally {
        sqlSession.close();
    }
}

From source file:org.geogit.rest.dispatch.GeogitDispatcher.java

@Override
public ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    try {/*from   w  w  w  . j a va 2  s  .c o  m*/
        converter.service(req, resp);
    } catch (Exception e) {
        RestletException re = null;
        if (e instanceof RestletException) {
            re = (RestletException) e;
        }
        if (re == null && e.getCause() instanceof RestletException) {
            re = (RestletException) e.getCause();
        }

        if (re != null) {
            resp.setStatus(re.getStatus().getCode());

            String reStr = re.getRepresentation().getText();
            if (reStr != null) {
                LOG.severe(reStr);
                resp.setContentType("text/plain");
                resp.getOutputStream().write(reStr.getBytes());
            }

            // log the full exception at a higher level
            LOG.log(Level.SEVERE, "", re);
        } else {
            LOG.log(Level.SEVERE, "", e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            if (e.getMessage() != null) {
                resp.getOutputStream().write(e.getMessage().getBytes());
            }
        }
        resp.getOutputStream().flush();
    }

    return null;
}

From source file:org.mypackage.spring.controllers.ContactsSpringController.java

@RequestMapping(value = "/contacts/{id}/delete", method = RequestMethod.GET)
public ModelAndView getDeleteContact(@PathVariable String id) {

    ModelAndView modelAndView = new ModelAndView();
    try {/* www  . j  a  v  a2s .c o m*/
        deleteContactController.deleteContact(id);
        modelAndView.setViewName("redirect:/contacts");
    } catch (DalException ex) {
        logger.error("A database error occured.", ex);
        modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        modelAndView.addObject("errorMessage", "An internal database error occured. Please try again.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedIdentifierException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST);
        modelAndView.addObject("errorMessage", "An error occured because of a malformed id (caused by id = "
                + id + "). Please use only numeric values.");
        modelAndView.setViewName("/errorPage.jsp");
    }
    return modelAndView;
}

From source file:com.pymegest.applicationserver.api.PuestoController.java

@RequestMapping(value = { "/Puesto" }, method = RequestMethod.GET)
public void findAll(HttpServletRequest request, HttpServletResponse response) {

    try {/*from  w  ww  . j  a  v a  2s.co m*/

        List<Puesto> puestos = puestoDAO.findAll();

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; chaset=UTF-8");

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(puestos);
        response.getWriter().println(json);

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptRemoveServlet.java

private void removeSingleFile(ResourceResolver resolver, SlingHttpServletResponse response, String fileName)
        throws IOException {
    if (StringUtils.isEmpty(fileName)) {
        ServletUtils.writeMessage(response, "error", "File name to be removed cannot be empty");
    } else {/*from  www. j  a v  a  2 s.c om*/
        final Script script = scriptFinder.find(fileName, resolver);
        if (script == null) {
            ServletUtils.writeMessage(response, "error", String.format("Script not found: '%s'", fileName));
        } else {
            final String scriptPath = script.getPath();

            try {
                scriptStorage.remove(script, resolver);

                ServletUtils.writeMessage(response, "success",
                        String.format("Script removed successfully: %s", scriptPath));
            } catch (RepositoryException e) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                ServletUtils.writeJson(response, String.format(
                        "Cannot remove script: '%s'." + " Repository error: %s", scriptPath, e.getMessage()));
            }
        }
    }
}

From source file:com.pymegest.applicationserver.api.SessionController.java

@RequestMapping(value = { "/Session" }, method = RequestMethod.DELETE)
public void delete(HttpServletRequest httpServletRequest, HttpServletResponse response) {

    try {//from   w  ww.  j a  va  2 s .  c om

        httpServletRequest.getSession(true).invalidate();

        response.setStatus(HttpServletResponse.SC_NO_CONTENT);

    } catch (Exception ex) {

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8");

        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.krawler.esp.servlets.ProfileImageServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the absolute path of the image
    ServletContext sc = getServletContext();
    String uri = req.getRequestURI();
    String servletBase = req.getServletPath();
    if (!StringUtil.isNullOrEmpty(req.getParameter("flag"))) {
        try {//from w  w w.  ja va2 s  . c o m
            // TODO: Fix hardcoded url
            if (!StringUtil.isNullOrEmpty(req.getParameter("trackid"))) {
                String url = "/remoteapi.jsp?action=100&data={\"iscommit\":true}&trackid="
                        + req.getParameter("trackid");
                RequestDispatcher rd = req.getRequestDispatcher(url);
                rd.include(req, resp);
            }
            String fileName = StorageHandler.GetProfileImgStorePath() + "blankImage.png";
            File file = new File(fileName);
            if (file.exists()) {
                FileInputStream in = new FileInputStream(file);
                OutputStream out = resp.getOutputStream();

                // Copy the contents of the file to the output stream
                byte[] buf = new byte[4096];
                int count = 0;
                while ((count = in.read(buf)) >= 0) {
                    out.write(buf, 0, count);
                }
                in.close();
                out.close();
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    } else {
        boolean Companyflag = (req.getParameter("company") != null) ? true : false;
        String imagePath = defaultImgPath;
        String requestedFileName = "";
        if (Companyflag) {
            imagePath = defaultCompanyImgPath;
            String companyId = null;
            try {
                companyId = sessionHandlerImpl.getCompanyid(req);
            } catch (Exception ee) {
                logger.warn(ee.getMessage(), ee);
            }
            if (StringUtil.isNullOrEmpty(companyId)) {
                String domain = URLUtil.getDomainName(req);
                if (!StringUtil.isNullOrEmpty(domain)) {
                    //@@@
                    //                        companyId = sessionHandlerImpl.getCompanyid(domain);
                    requestedFileName = "/original_" + companyId + ".png";
                } else {
                    requestedFileName = "logo.gif";
                }
            } else {
                requestedFileName = "/" + companyId + ".png";
            }
        } else {
            requestedFileName = uri.substring(uri.lastIndexOf(servletBase) + servletBase.length());
        }
        String fileName = null;

        fileName = StorageHandler.GetProfileImgStorePath() + requestedFileName;
        // Get the MIME type of the image
        String mimeType = sc.getMimeType(fileName);
        if (mimeType == null) {
            sc.log("Could not get MIME type of " + fileName);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // Set content type
        resp.setContentType(mimeType);

        // Set content size
        File file = new File(fileName);
        if (!file.exists()) {
            if (fileName.contains("_100.")) {
                file = new File(fileName.replaceAll("_100.", "."));
            }
            if (!file.exists()) {
                file = new File(sc.getRealPath(imagePath));
            }
        }

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

        // Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[4096];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.close();
    }
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.datafile.DataFileServiceController.java

/**
 * Exception handler for RestServiceException.class.
 * Writes exception message into HTTP response.
 *
 * @param ex       exception body/*  w  w  w.  j  a  va 2 s  . com*/
 * @param response HTTP response
 * @throws IOException error while writing into response
 */
@ExceptionHandler(RestServiceException.class)
public void handleException(RestServiceException ex, HttpServletResponse response) throws IOException {
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    log.error(ex);
}

From source file:com.pymegest.applicationserver.api.FamiliaController.java

@RequestMapping(value = { "/Familia" }, method = RequestMethod.GET)
public void findAll(HttpServletRequest request, HttpServletResponse response) {

    try {/*from   www . jav  a  2  s  .  c  o m*/

        List<Familia> familias = familiaDAO.findAll();

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; chaset=UTF-8");

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(familias);
        response.getWriter().println(json);

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:eu.stratosphere.nephele.jobmanager.web.QosStatisticsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from   w  w w.j a  v  a2 s  . c o m
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/json");

        JSONObject jobs = new JSONObject();
        JobID job;
        long startTimestamp = -1;

        if (req.getParameter("job") != null && !req.getParameter("job").isEmpty())
            job = JobID.fromHexString(req.getParameter("job"));
        else
            job = getLastCreatedJob();

        if (req.getParameter("startTimestamp") != null && !req.getParameter("startTimestamp").isEmpty())
            startTimestamp = Long.parseLong(req.getParameter("startTimestamp"));

        for (JobID id : jobStatistics.keySet()) {
            JSONObject jobDetails = jobStatistics.get(id).getJobMetadata();

            if (job != null && job.equals(id)) {
                if (startTimestamp > 0)
                    jobStatistics.get(id).getStatistics(jobDetails, startTimestamp);
                else
                    jobStatistics.get(id).getStatistics(jobDetails);
            }

            jobs.put(id.toString(), jobDetails);
        }

        JSONObject result = new JSONObject();
        if (job != null && jobStatistics.containsKey(job)) {
            result.put("currentJob", job);
            result.put("refreshInterval", jobStatistics.get(job).getRefreshInterval());
            result.put("maxEntriesCount", jobStatistics.get(job).getMaxEntriesCount());
        } else {
            result.put("refreshInterval", INITIAL_REFRESH_INTERVAL);
            result.put("maxEntriesCount", 0);
        }
        result.put("jobs", jobs);
        result.write(resp.getWriter());

    } catch (JSONException e) {
        LOG.error("JSON Error: " + e.getMessage(), e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.setContentType("application/json");
        resp.getWriter().println("{ status: \"internal error\", message: \"" + e.getMessage() + "\" }");
    }
}