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.wso2telco.workflow.api.WorkflowHistoryAPI.java

@GET
@Path("/apis/{subscriberName}")
@Produces(MediaType.APPLICATION_JSON)//ww w.  ja va2  s .c  om
public Response getAPIsBySubscriber(@PathParam("subscriberName") String subscriberName) {

    String jsonPayload;
    try {
        List<String> apis = SbHostObjectUtils.getAPIsBySubscriber(subscriberName);
        jsonPayload = new Gson().toJson(apis);
    } catch (Exception e) {
        log.error(e);
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
    return Response.status(HttpServletResponse.SC_OK).entity(jsonPayload).build();
}

From source file:com.ebay.pulsar.metric.servlet.MetricRestServlet.java

private void getCounters(final HttpServletRequest request, final String pathInfo,
        final HttpServletResponse response) throws Exception {
    String queryString = request.getQueryString();
    QueryParam queryParam = getCassandraQueryParam(queryString);
    ListenableFuture<List<Counter>> future = metricService.findCounters(
            (String) queryParam.getParameters().get(QueryParam.METRIC_NAME),
            (String) queryParam.getParameters().get(QueryParam.GROUP_ID));
    try {//from   w w w  .j a  va 2 s. co  m
        List<Counter> counters = future.get(5000, TimeUnit.MILLISECONDS);
        String result = counterResultWriter.writeValueAsString(counters);
        response.getWriter().print(result);
        response.setContentLength(result.length());
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (TimeoutException e) {
        response.getWriter().print(QUERY_CASSANDRA_TIMEOUT);
        response.setContentLength(QUERY_CASSANDRA_TIMEOUT.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ExecutionException e) {
        response.getWriter().print(QUERY_CASSANDRA_ERROR);
        response.setContentLength(QUERY_CASSANDRA_ERROR.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

@RequestMapping(value = { "/Familia/{idsFamilias}" }, method = RequestMethod.DELETE)
public void delete(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsFamilias") String idsFamiliasStr) {

    try {/*from   w ww  .j av a  2  s.co  m*/
        String[] idsFamiliasArr = idsFamiliasStr.split(",");
        for (int i = 0; i < idsFamiliasArr.length; i++) {
            familiaDAO.delete(Integer.parseInt(idsFamiliasArr[i]));
        }

        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:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@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)) {
        // 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  ww . j  av a  2 s. c  om
            ArrayList<String> 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(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(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.pymegest.applicationserver.api.UsuarioController.java

@RequestMapping(value = { "/Usuario/{idsUsuarios}" }, method = RequestMethod.DELETE)
public void delete(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsUsuarios") String idsUsuariosStr) {

    try {//from   w  ww.  j a  v a2 s.c  om
        String[] idsUsuariosArr = idsUsuariosStr.split(",");
        for (int i = 0; i < idsUsuariosArr.length; i++) {
            usuarioDAO.delete(Integer.parseInt(idsUsuariosArr[i]));
        }

        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.pymegest.applicationserver.api.ProductoController.java

@RequestMapping(value = { "/Producto/{idsProductos}" }, method = RequestMethod.DELETE)
public void delete(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsProductos") String idsProductosStr) {

    try {/* w w w . j a  v a 2s  . c om*/
        String[] idsProductosArr = idsProductosStr.split(",");
        for (int i = 0; i < idsProductosArr.length; i++) {
            productoDAO.delete(Integer.parseInt(idsProductosArr[i]));
        }

        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.pymegest.applicationserver.api.EmpleadoController.java

@RequestMapping(value = { "/Empleado/{idsEmpleados}" }, method = RequestMethod.DELETE)
public void delete(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsEmpleados") String idsEmpleadosStr) {

    try {//from   w w w  .j a  v a2s. c o m

        String[] idsEmpleadosArr = idsEmpleadosStr.split(",");
        for (int i = 0; i < idsEmpleadosArr.length; i++) {
            empleadoDAO.delete(Integer.parseInt(idsEmpleadosArr[i]));
        }

        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:org.openrepose.filters.authz.RequestAuthorizationHandler.java

@Override
public FilterDirector handleRequest(HttpServletRequest request, ReadableHttpServletResponse response) {
    final FilterDirector myDirector = new FilterDirectorImpl();
    myDirector.setFilterAction(FilterAction.RETURN);
    myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    String message = "Failure in authorization component";

    final String tracingHeader = request.getHeader(CommonHttpHeader.TRACE_GUID.toString());
    final String authenticationToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());

    try {//from  ww w  . j a  v a 2 s. c  o  m
        if (StringUtilities.isBlank(authenticationToken)) {
            // Reject if no token
            message = "Authentication token not found in X-Auth-Token header. Rejecting request.";
            LOG.debug(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
        } else if (adminRoleMatchIgnoringCase(request.getHeaders(OpenStackServiceHeader.ROLES.toString()))
                || isEndpointAuthorizedForToken(authenticationToken, tracingHeader)) {
            myDirector.setFilterAction(FilterAction.PASS);
        } else {
            message = "User token: " + authenticationToken
                    + ": The user's service catalog does not contain an endpoint that matches "
                    + "the endpoint configured in openstack-authorization.cfg.xml: \""
                    + configuredEndpoint.getHref() + "\".  User not authorized to access service.";
            LOG.info(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (AuthServiceOverLimitException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // (503)
        String retry = ex.getRetryAfter();
        if (retry == null) {
            Calendar retryCalendar = new GregorianCalendar();
            retryCalendar.add(Calendar.SECOND, 5);
            retry = new HttpDate(retryCalendar.getTime()).toRFC1123();
        }
        myDirector.responseHeaderManager().appendHeader(HttpHeaders.RETRY_AFTER, retry);
    } catch (AuthServiceException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        if (ex.getCause() instanceof AkkaServiceClientException
                && ex.getCause().getCause() instanceof TimeoutException) {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        } else {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (Exception ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (delegating != null && myDirector.getFilterAction() != FilterAction.PASS) {
        myDirector.setFilterAction(FilterAction.PASS);
        for (Map.Entry<String, List<String>> mapHeaders : JavaDelegationManagerProxy
                .buildDelegationHeaders(myDirector.getResponseStatusCode(), CLIENT_AUTHORIZATION, message,
                        delegating.getQuality())
                .entrySet()) {
            List<String> value = mapHeaders.getValue();
            myDirector.requestHeaderManager().appendHeader(mapHeaders.getKey(),
                    value.toArray(new String[value.size()]));
        }
    }
    return myDirector;
}

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

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    auditService = getAuditService();/*w w  w. ja v a2 s.  c om*/
    JSONObject jsonResponse = new JSONObject();

    WebPageInfo pageInfo = new WebPageInfo(cleanGetParameter(req, PAGE_POSITION_PARAMETER),
            cleanGetParameter(req, PAGE_SIZE_PARAMETER));

    try {

        try {
            JSONObject resultsObject = new JSONObject();
            jsonResponse.put(RESULTS_TAG, resultsObject);

            JSONArray resultsArray = new JSONArray();
            resultsObject.put(AUDIT_ENTRIES_KEY, resultsArray);

            long auditEntryCount = auditService.getAuditEntryCount();

            resultsObject.put(AUDIT_TRAIL_SIZE_KEY, auditEntryCount);

            List<AuditEntry> results = auditService.getMostRecentByPage(pageInfo.getPageSize(),
                    pageInfo.getPagePos() - 1);
            for (AuditEntry entry : results) {
                resultsArray.put(createAuditEntryJSONObject(entry));
            }
            String resultsString;
            if (results.size() > 0) {
                final String firstId = results.get(0).getIdentifier();
                final String lastId = results.get(results.size() - 1).getIdentifier();
                resultsString = firstId + "-" + lastId;
            } else {
                resultsString = "no entries retrieved";
            }
            pageInfo.setItemTotal(auditEntryCount);
            jsonResponse.put(WebPageInfo.PAGING_LABEL, pageInfo.getPageJSON());
            auditService.addEvent(AuditService.AUDIT_LOG_QUERY, getPermissionService().getCurrentUsername(),
                    resultsString);
        } catch (AuditServiceException e) {
            LOGGER.error("error creating audit entry ", e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "error creating audit entry " + "; see server logs");

            // if we get an exception, to maintain security do not return
            // any results
            jsonResponse.put(RESULTS_TAG, (JSONObject) null);
        }

    } catch (JSONException e) {
        LOGGER.error("JSONException", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "error transcribing audit trail entries to JSON; see server logs");
    } finally {
        // set Response
        String jsonResultString = jsonResponse.toString();
        try {
            resp.getWriter().write(jsonResultString);
        } catch (IOException e) {
            LOGGER.error("Could not write JSON response");
        }

    }

}

From source file:org.magnum.dataup.VideoUpController.java

@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.GET)
public void getData(@PathVariable(VideoSvcApi.ID_PARAMETER) long id, HttpServletResponse resp) {
    if (videos.containsKey(id)) {
        try {/* w ww .  ja  v a  2 s  .  co m*/
            serveVideo(videos.get(id), resp);
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setHeader("Content-Type", "video/mpeg");
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}