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.oneops.ecv.ws.StatusController.java

@ExceptionHandler(ConfigException.class)
@ResponseBody//from   w  ww. j av a  2s .  co  m
public void handleConfigException(ConfigException e, HttpServletResponse response) throws IOException {
    ECV_LOGGER.error(e);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().write(e.getMessage());
}

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

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final String messageId = req.getParameter(PARAM_MSG_ID);
    final MessageRetrieverService retriever = getMessageRetrieverService();

    try {//from  w ww. jav a2 s . co m
        final Message message = retriever.retrieve(messageId);

        JSONArray attachments = new JSONArray();

        for (AttachmentSummary attachment : message.getContentHeader().getAttachmentSummaries()) {
            JSONObject attachmentObject = new JSONObject();

            String filename = attachment.getFileName();
            if (filename == null || filename.isEmpty()) {
                final String positionString = attachment.getPositionString();

                // TODO: revisit this logic; best to assume first attachment
                // is body?
                if (positionString.isEmpty() || positionString.equals("1")) {
                    filename = "Message-Body";
                } else {
                    filename = "attachment-" + positionString;
                }
            }

            String mimeType = attachment.getMimeType();
            if (mimeType == null) {
                mimeType = "";
            }

            attachmentObject.put(KEY_UUID, attachment.getUuid());
            attachmentObject.put(KEY_FILE_NAME, filename);
            attachmentObject.put(KEY_MIME_TYPE, mimeType);
            attachments.put(attachmentObject);
        }

        JSONObject jObject = new JSONObject();
        jObject.put(WebConstants.DATA_TAG, attachments);
        String jsonString = jObject.toString();
        resp.getWriter().write(jsonString);
    } catch (CannotRetrieveException e) {
        respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp);
        LOGGER.error("Could not retrieve attachment", e);
    } catch (JSONException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
        LOGGER.error("Could not retrieve attachment", e);
    }
}

From source file:edu.iastate.airl.semtus.server.UploadServiceController.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // 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  w w  w . j a va2s  . c om
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField())
                    continue;

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(Utils.UPLOAD_DIRECTORY, fileName);

                // first clean-up the folder; we want no clutter on the server :-)
                String[] ls = new File(Utils.UPLOAD_DIRECTORY).list();

                for (int idx = 0; idx < ls.length; idx++) {

                    File file = new File(Utils.UPLOAD_DIRECTORY, ls[idx]);
                    file.delete();
                }

                if (uploadedFile.createNewFile()) {

                    item.write(uploadedFile);
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.getWriter().print("The file was created successfully.");
                    resp.flushBuffer();

                } else {

                    throw new IOException("The file already exists in repository.");
                }
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:de.devbliss.apitester.dummyserver.DummyRequestHandler.java

private void handleException(Exception e, HttpServletResponse response) throws IOException {
    response.setContentType(CONTENT_TYPE_ERROR);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().write("exception type: " + e.getClass());
    response.getWriter().write(e.getMessage());
}

From source file:info.raack.appliancedetection.evaluation.web.BaseController.java

@ExceptionHandler
public ModelAndView handleUncaughtException(Exception ex, HttpServletRequest request,
        HttpServletResponse response) {/* w w w  .j  a v  a2  s . c  om*/

    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    errorService.reportError("Error", URGENCY.URGENT, ex);
    logger.error("An exception was caught while processing", ex);

    return new ModelAndView("error", new ModelMap());
}

From source file:org.sventon.web.ctrl.RSSController.java

@Override
protected ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response,
        final Object cmd, final BindException errors) throws Exception {

    logger.debug("Getting RSS feed");

    final RevisionRangeCommand command = (RevisionRangeCommand) cmd;
    logger.debug(command);/*w  ww.  ja v  a  2 s  .  co  m*/

    if (!application.isConfigured()) {
        handleError(response, "sventon has not been configured yet!");
        return null;
    }

    final RepositoryConfiguration configuration = application.getConfiguration(command.getName());
    if (configuration == null) {
        handleError(response, "Repository [" + command.getName() + "] does not exist!");
        return null;
    }

    addResponseHeaders(response);

    SVNConnection connection = null;

    try {
        final List<LogEntry> logEntries = new ArrayList<LogEntry>();
        connection = createRepositoryConnection(request, configuration);
        final Long headRevision = getRepositoryService().getLatestRevision(connection);
        command.setRevision(
                getRepositoryService().translateRevision(connection, command.getRevision(), headRevision));

        logger.debug("Outputting feed for [" + command.getPath() + "]");
        logEntries.addAll(getRepositoryService().getLogEntries(connection, command.getName(),
                command.getRevisionNumber(), command.getStopRevision().getNumber(), command.getPath(),
                configuration.getRssItemsCount(), false, true));
        rssFeedGenerator.outputFeed(configuration, logEntries, request, response);
    } catch (AuthenticationException aex) {
        logger.info(aex.getMessage());
        httpAuthenticationHandler.sendChallenge(response);
    } catch (NoSuchRevisionException nsre) {
        logger.info(nsre.getMessage());
    } catch (SventonException svnex) {
        logger.debug(svnex.getMessage(), svnex);
        logger.error(svnex.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to generate RSS feed");
    } finally {
        close(connection);
    }
    return null;
}

From source file:org.opendatakit.api.offices.OfficeService.java

@GET
@Path("/")
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
@ApiOperation(value = "Get list of all offices.", response = RegionalOffice.class, responseContainer = "List")
public Response getList() throws IOException {
    Datastore ds = callingContext.getDatastore();
    User user = callingContext.getCurrentUser();
    List<RegionalOffice> regionalOffices = new ArrayList<RegionalOffice>();
    try {/*  ww w . j  av  a  2 s  .  c  om*/
        OdkRegionalOfficeTable.assertRelation(callingContext);
        OdkRegionalOfficeTable regionalOfficeTable = OdkRegionalOfficeTable.assertRelation(callingContext);
        Query q = ds.createQuery(regionalOfficeTable, "OdkRegionalOfficeTable.getAllOffices", user);
        List<? extends CommonFieldsBase> l = q.executeQuery();
        for (CommonFieldsBase cb : l) {
            OdkRegionalOfficeTable t = (OdkRegionalOfficeTable) cb;
            RegionalOffice i = new RegionalOffice(t.getUri(), t.getRegionalOfficeName(),
                    t.getRegionalOfficeId());
            regionalOffices.add(i);
        }
    } catch (ODKDatastoreException e) {
        logger.error("Error retrieving ", e);
        throw new WebApplicationException(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString(),
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return Response.ok().entity(regionalOffices).encoding(BasicConsts.UTF8_ENCODE)
            .type(MediaType.APPLICATION_JSON)
            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
            .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
            .build();
}

From source file:de.highbyte_le.weberknecht.ControllerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    if (log.isDebugEnabled())
        log.debug("doFilter() - start");

    long start = System.currentTimeMillis();

    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
        throw new IllegalArgumentException("no http request");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    DbConnectionHolder conHolder = new DbConnectionHolder(core.getDbConnectionProvider());
    try {/*from w w w  .j ava2s .c om*/
        Router router = core.createRouter(conHolder); //choose router depending on config
        RoutingTarget routingTarget = router.routeUri(httpRequest);
        if (null == routingTarget) {
            filterChain.doFilter(request, response);
        } else {
            core.executeAction(httpRequest, httpResponse, conHolder, routingTarget);

            long finish = System.currentTimeMillis();
            if (log.isInfoEnabled()) {
                log.info("service() - page delivery of '" + httpRequest.getRequestURI() + "' took "
                        + (finish - start) + " ms");
            }
        }
    } catch (Exception e1) {
        try {
            log.error("service() - exception while error handler instantiation: " + e1.getMessage(), e1); //$NON-NLS-1$

            //exceptions occurring here were not processed by weberknecht error handlers.
            //so it is probably a good idea to go on with the error handling of the container. 
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); //call error page 500
        } catch (IOException e) {
            log.error("service() - IOException: " + e.getMessage(), e); //$NON-NLS-1$
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); //just return 500
        }
    } finally {
        try {
            conHolder.close();
        } catch (SQLException e) {
            log.error("service() - SQLException while closing db connection: " + e.getMessage()); //$NON-NLS-1$
        }
    }
}

From source file:cn.webwheel.DefaultMain.java

/**
 * Wrap exception to a json object and return it to client.
 * <p>/*  ww w  .  jav a2 s .  com*/
 * <b>json object format:</b><br/>
 * <p><blockquote><pre>
 *     {
 *         "msg": "the exception's message",
 *         "stackTrace":[
 *             "exception's stack trace1",
 *             "exception's stack trace2",
 *             "exception's stack trace3",
 *             ....
 *         ]
 *     }
 * </pre></blockquote></p>
 */
public Object executeActionError(WebContext ctx, ActionInfo ai, Object action, Throwable e) throws Throwable {
    if (e instanceof LogicException) {
        return ((LogicException) e).getResult();
    }
    Logger.getLogger(DefaultMain.class.getName()).log(Level.SEVERE, "action execution error", e);
    StringBuilder sb = new StringBuilder();
    sb.append("{\n");
    String s;
    try {
        s = JsonResult.objectMapper.writeValueAsString(e.toString());
    } catch (IOException e1) {
        s = "\"" + e.toString().replace("\"", "'") + "\"";
    }
    sb.append("    \"msg\" : " + s + ",\n");
    sb.append("    \"stackTrace\" : [");
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String[] ss = sw.toString().split("\r\n");
    for (int i = 1; i < ss.length; i++) {
        if (sb.charAt(sb.length() - 1) != '[') {
            sb.append(',');
        }
        sb.append("\n        ").append(JsonResult.objectMapper.writeValueAsString(ss[i]));
    }
    sb.append("\n    ]\n");
    sb.append("}");
    HttpServletResponse response = ctx.getResponse();
    if (JsonResult.defWrapMultipart && ServletFileUpload.isMultipartContent(ctx.getRequest())
            && !"XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))) {
        response.setContentType("text/html");
        sb.insert(0, "<textarea>\n");
        sb.append("\n</textarea>");
    } else {
        response.setContentType("application/json");
    }
    response.setCharacterEncoding("utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().write(sb.toString());
    return EmptyResult.inst;
}

From source file:com.thoughtworks.go.server.security.BasicAuthenticationFilter.java

public void handleException(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Exception e)
        throws IOException {
    String message = localizer.localize("AUTHENTICATION_ERROR");
    if (hasAccept(httpRequest, "text/html") || hasAccept(httpRequest, "application/xhtml")) {
        httpRequest.getSession().setAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY,
                new RuntimeException(message));
        httpRequest.setAttribute(SessionDenialAwareAuthenticationProcessingFilterEntryPoint.SESSION_DENIED,
                true);/* w  ww  . jav  a2  s.co m*/

        httpResponse.sendRedirect("/go/auth/login?login_error=1");
        return;
    }
    if (hasAccept(httpRequest, "application/vnd.go.cd.v1+json") || hasAccept(httpRequest, "application/json")) {
        String msg = String.format("{\n \"message\": \"%s\"\n}\n", message);
        generateResponse(httpResponse, "application/vnd.go.cd.v1+json; charset=utf-8", msg);
        return;
    }
    if (hasAccept(httpRequest, "application/xml")) {
        String msg = String.format("<message>%s</message>\n", message);
        generateResponse(httpResponse, "application/xml; charset=utf-8", msg);
        return;
    }

    httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}