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:eionet.cr.web.action.TabularDataServlet.java

/**
 *
 * @param exception/*from  w  ww.  j av  a  2  s .co m*/
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void handleException(Exception exception, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOGGER.error(exception);

    if (Util.isWebBrowser(request)) {
        request.setAttribute(StripesExceptionHandler.EXCEPTION_ATTR, exception);
        request.getRequestDispatcher(StripesExceptionHandler.ERROR_PAGE).forward(request, response);
    } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.epam.catgenome.controller.util.MultipartFileSender.java

public void serveResource() throws IOException {
    if (response == null || request == null) {
        return;/*from  ww  w  .  ja v  a 2  s .c  om*/
    }

    if (!Files.exists(filepath)) {
        logger.error("File doesn't exist at URI : {}", filepath.toAbsolutePath().toString());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Long length = Files.size(filepath);
    String fileName = filepath.getFileName().toString();
    FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = LocalDateTime
            .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId()))
            .toEpochSecond(ZoneOffset.UTC);
    //String contentType = MimeTypeUtils.probeContentType(filepath);
    String contentType = null;

    // Validate request headers for caching ---------------------------------------------------
    if (!validateHeadersCaching(fileName, lastModified)) {
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    if (!validateHeadersResume(fileName, lastModified)) {
        return;
    }

    // Validate and process range -------------------------------------------------------------
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = processRange(length, fileName, full);
    if (ranges == null) {
        return;
    }

    // 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";
    }
    logger.debug("Content-Type : {}", contentType);
    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    logger.debug("Content-Disposition : {}", disposition);
    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.
    try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
            OutputStream output = response.getOutputStream()) {

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

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

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

            // Return single part of file.
            Range r = ranges.get(0);
            logger.info("Return 1 part of file : from ({}) to ({})", r.start, r.end);
            response.setContentType(contentType);
            response.setHeader(CONTENT_RANGE_HEADER, "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.
            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) {
                logger.info("Return multi part of file : from ({}) to ({})", r.start, r.end);
                // 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.
                Range.copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    }

}

From source file:com.portfolio.security.LTIv2Servlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuffer outTrace = new StringBuffer();
    String logFName = null;/*from w w w  . jav  a 2 s  .c o m*/
    HttpSession session = request.getSession(true);
    String ppath = session.getServletContext().getRealPath("/");
    String outsideDir = ppath.substring(0, ppath.lastIndexOf("/")) + "_files/";

    ServletContext application = getServletConfig().getServletContext();

    //super.doPost(request, response);
    logFName = outsideDir + "logs/logLTI2.txt";
    outTraceFormattedMessage(outTrace, "doPost() - " + logFName);

    String toolProxyPath = outsideDir + "tool_proxy.txt";

    try {
        //         wadbackend.WadUtilities.setApplicationAttributes(application, session);
        doRequest(request, response, session, application, toolProxyPath, outTrace);
    } catch (Exception e) {
        String ipAddress = request.getRemoteAddr();
        String uri = request.getRequestURI();
        M_log.warn("General LTI2 Failure URI=" + uri + " IP=" + ipAddress);
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        doErrorJSON(request, response, null, "General failure", e);
    } finally {
        outTraceFormattedMessage(outTrace, "In finally()");
        if (LTIServletUtils.isTrace(application)) {
            outTraceFormattedMessage(outTrace, "In finally() with trace");
            //            wadbackend.WadUtilities.appendlogfile(logFName, "POSTlti:" + outTrace.toString());
        }
    }
}

From source file:fr.gael.dhus.api.UploadController.java

@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {//from   ww w. java2 s .  c  o m
            ArrayList<Long> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(new Long(cid));
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(user.getId(), product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            logger.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            logger.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            logger.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:com.linuxbox.enkive.web.KeyNameServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("KeyNameServlet doGet started");
    }/*from www .  ja  v  a 2s. c  om*/

    try {
        try {
            Set<GathererAttributes> attributes = client.getAttributes();
            JSONArray result = new JSONArray();

            for (GathererAttributes attribute : attributes) {
                if (!attribute.getName().equals("CollectionStatsGatherer")) {
                    Map<String, Object> keyMethods = new HashMap<String, Object>();
                    for (ConsolidationKeyHandler key : attribute.getKeys()) {
                        String builtKey = "";
                        for (String keyPart : key.getKey()) {
                            builtKey = builtKey + keyPart + ".";
                        }
                        builtKey = builtKey.substring(0, builtKey.length() - 1);
                        if (key.getMethods() != null) {
                            Map<String, Object> methodsMap = new HashMap<String, Object>();
                            Map<String, Object> innerKeyMap = new HashMap<String, Object>();
                            innerKeyMap.put("methods", (String[]) key.getMethods().toArray());
                            innerKeyMap.put("units", key.getUnits());
                            methodsMap.put(builtKey, innerKeyMap);
                            keyMethods.put(key.getHumanKey(), methodsMap);
                        }
                    }
                    Map<String, Object> dataTemp = new HashMap<String, Object>();
                    dataTemp.put(attribute.getName(), keyMethods);
                    Map<String, Object> humanKeyWrapper = new HashMap<String, Object>();
                    humanKeyWrapper.put(attribute.getHumanName(), dataTemp);
                    result.put(humanKeyWrapper);
                }
            }

            try {
                JSONObject statistics = new JSONObject();
                statistics.put("results", result);
                resp.getWriter().write(statistics.toString());
            } catch (IOException e) {
                // FIXME: NOAHCODE Why is this calling respondError and
                // throwing an exception, the catch of which calls
                // respondError again?
                respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
                throw new CannotRetrieveException("could not create JSON for message attachment", e);
            } catch (JSONException e) {
                // FIXME: NOAHCODE Why is this calling respondError and
                // throwing an exception, the catch of which calls
                // respondError again?
                respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
                throw new CannotRetrieveException("could not create JSON for message attachment", e);
            }
        } catch (CannotRetrieveException e) {
            respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp);
            LOGGER.error("CannotRetrieveException", e);
        } catch (NullPointerException e) {
            respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
            LOGGER.error("NullException thrown", e);
        }
    } catch (IOException e) {
        LOGGER.error("IOException thrown", e);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("StatsServlet doGet finished");
    }
}

From source file:com.ephesoft.gxt.systemconfig.server.ExportRegexPoolServlet.java

/**
 * Overridden doGet method./*  ww w .java 2  s  . c  o m*/
 */
@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    final RegexGroupService regexGroupService = this.getSingleBeanOfType(RegexGroupService.class);
    final List<RegexGroup> regexGroupList = regexGroupService.getRegexGroups();

    if (regexGroupList == null) {
        LOGGER.error("Regex group list is null.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Regex group list is null.");
    } else {
        try {
            final Calendar cal = Calendar.getInstance();
            final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

            final SimpleDateFormat formatter = new SimpleDateFormat(CoreCommonConstant.DATE_FORMAT);
            final String formattedDate = formatter.format(new Date());
            final String zipFileName = StringUtil.concatenate(SystemConfigConstants.REGEX_POOL,
                    CoreCommonConstant.UNDERSCORE, formattedDate, CoreCommonConstant.UNDERSCORE,
                    cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.SECOND));
            final String tempFolderLocation = StringUtil.concatenate(exportSerailizationFolderPath,
                    File.separator, zipFileName);
            final File copiedFolder = new File(tempFolderLocation);

            if (copiedFolder.exists()) {
                copiedFolder.delete();
            }

            // Setting the parent of regex pattern list to null for exporting
            RegexUtil.exportRegexPatterns(regexGroupList);

            // Setting the id of regex group list to "0" for exporting
            for (final RegexGroup regexGroup : regexGroupList) {
                regexGroup.setId(0);
            }
            copiedFolder.mkdirs();

            final File serializedExportFile = new File(tempFolderLocation + File.separator
                    + SystemConfigConstants.REGEX_POOL + SystemConfigConstants.SERIALIZATION_EXT);

            try {
                SerializationUtils.serialize((Serializable) regexGroupList,
                        new FileOutputStream(serializedExportFile));
                final File originalFolder = new File(
                        StringUtil.concatenate(batchSchemaService.getBaseSampleFDLock(), File.separator,
                                SystemConfigConstants.REGEX_POOL));

                if (originalFolder.isDirectory()) {
                    final String[] folderList = originalFolder.list();
                    Arrays.sort(folderList);
                }
            } catch (final FileNotFoundException fileNotFoundException) {
                // Unable to read serializable file
                LOGGER.error("Error occurred while creating the serializable file." + fileNotFoundException,
                        fileNotFoundException);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error occurred while creating the serializable file.");
            }

            resp.setContentType(SystemConfigConstants.APPLICATION_X_ZIP);
            resp.setHeader(SystemConfigConstants.CONTENT_DISPOSITION,
                    StringUtil.concatenate(SystemConfigConstants.ATTACHMENT_FILENAME, zipFileName,
                            SystemConfigConstants.ZIP_EXT, SystemConfigConstants.HEADER_MODE));
            ServletOutputStream out = null;
            ZipOutputStream zipOutput = null;
            try {
                out = resp.getOutputStream();
                zipOutput = new ZipOutputStream(out);
                FileUtils.zipDirectory(tempFolderLocation, zipOutput, zipFileName);
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (final IOException ioException) {
                // Unable to create the temporary export file(s)/folder(s)
                LOGGER.error("Error occurred while creating the zip file." + ioException, ioException);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Unable to export.Please try again.");
            } finally {
                // clean up code
                if (zipOutput != null) {
                    zipOutput.close();
                }
                if (out != null) {
                    out.flush();
                }
                FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
            }
        } catch (final Exception exception) {
            LOGGER.error("ERROR IN EXPORT:  " + exception, exception);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        }
    }
}

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

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

    try {/*from  ww  w  .  j a va 2  s . c o m*/

        Integer idUsuario = (Integer) httpServletRequest.getSession(true).getAttribute("idUduario");

        Usuario usuario = usuarioDAO.read(idUsuario);

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

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(usuario);
        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.freme.common.security.AuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = asHttp(request);
    HttpServletResponse httpResponse = asHttp(response);

    Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username"));
    Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password"));
    Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token"));

    if (httpRequest.getParameter("token") != null) {
        token = Optional.fromNullable(httpRequest.getParameter("token"));
    }//  w  w w  .  ja  v a  2  s  .co  m

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);

    try {
        //            if (postToAuthenticate(httpRequest, resourcePath)) {
        //                logger.debug("Trying to authenticate user {} by X-Auth-Username method", username);
        //                processUsernamePasswordAuthentication(httpResponse, username, password);
        //                return;
        //            }

        if (token.isPresent()) {
            logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token);
            processTokenAuthentication(token);
        }

        logger.debug("AuthenticationFilter is passing request down the filter chain");
        addSessionContextToLogging();
        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", internalAuthenticationServiceException);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException authenticationException) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    } finally {
        MDC.remove(TOKEN_SESSION_KEY);
        MDC.remove(USER_SESSION_KEY);
    }
}

From source file:com.cognifide.aet.rest.ConfigsServlet.java

/***
 * Returns JSON representation of Suite based on correlationId or suite name.
 * If suite name is provided, then newest version of JSON is returned.
 *
 * @param req//from   w  ww . java2  s  .co  m
 * @param resp
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    LOGGER.debug("GET, req: '{}'", req);
    PrintWriter responseWriter = retrieveResponseWriter(req, resp);
    if (responseWriter != null) {
        resp.setContentType("application/json");
        String configType = StringUtils.substringAfter(req.getRequestURI(), Helper.getConfigsPath())
                .replace(Helper.PATH_SEPARATOR, "");
        String reportDomain = reportConfigurationManager.getReportDomain();

        if (COMMUNICATION_SETTINGS_PARAM.equals(configType)) {
            JmsEndpointConfig jmsEndpointConfig = jmsConnection.getEndpointConfig();
            CommunicationSettings communicationSettings = new CommunicationSettings(jmsEndpointConfig,
                    reportDomain);
            responseWriter.write(new Gson().toJson(communicationSettings));
        } else if (LIST_PARAM.equals(configType)) {
            resp.setContentType("text/html; charset=utf-8");
            resp.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
            responseWriter.write(new SuitesListProvider(metadataDAO, reportDomain).listSuites());
        } else if (LOCKS_PARAM.equals(configType)) {
            responseWriter.write(getLocks());
        } else {
            resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
            responseWriter.write("Unable to get given config.");
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    flushResponseBuffer(req, resp);
}