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:org.openmhealth.reference.filter.ExceptionFilter.java

/**
 * <p>//  ww  w.java 2  s  .c  om
 * If the request throws an exception, specifically a OmhException,
 * attempt to respond with that message from the exception.
 * </p>
 * 
 * <p>
 * For example, HTTP responses have their status codes changed to
 * {@link HttpServletResponse#SC_BAD_REQUEST} and the body of the response
 * is the error message.
 * </p>
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    // Get a handler for the correct exception type.
    Throwable exception = null;

    // Always let the request continue but setup to catch exceptions.
    try {
        chain.doFilter(request, response);
    }
    // The servlet container may wrap the exception, in which case we
    // must first unwrap it, then delegate it.
    catch (NestedServletException e) {
        // Get the underlying cause.
        Throwable cause = e.getCause();

        // If the underlying exception is one of ours, then store the
        // underlying exception.
        if (cause instanceof OmhException) {
            exception = cause;
        }
        // Otherwise, store this exception.
        else {
            exception = e;
        }
    }
    // Otherwise, store the exception,
    catch (Exception e) {
        exception = e;
    }

    // If an exception was thrown, attempt to handle it.
    if (exception != null) {
        // Save the exception in the request.
        request.setAttribute(ATTRIBUTE_KEY_EXCEPTION, exception);

        // Handle the exception.
        if (exception instanceof NoSuchSchemaException) {
            LOGGER.log(Level.INFO, "An unknown schema was requested.", exception);

            // Respond to the user.
            sendResponse(response, HttpServletResponse.SC_NOT_FOUND, exception.getMessage());
        } else if (exception instanceof InvalidAuthenticationException) {
            LOGGER.log(Level.INFO, "A user's authentication information was invalid.", exception);

            // Respond to the user.
            sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
        } else if (exception instanceof InvalidAuthorizationException) {
            LOGGER.log(Level.INFO, "A user's authorization information was invalid.", exception);

            // Respond to the user.
            sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
        } else if (exception instanceof OmhException) {
            LOGGER.log(Level.INFO, "An invalid request was made.", exception);

            // Respond to the user.
            sendResponse(response, HttpServletResponse.SC_BAD_REQUEST, exception.getMessage());
        }
        // If the exception was not one of ours, the server must have
        // crashed.
        else {
            LOGGER.log(Level.SEVERE, "The server threw an unexpected exception.", exception);

            // Respond to the user.
            sendResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
        }
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.AsicContainerClientRequestProcessor.java

@Override
public void process() throws Exception {
    try {/*from  w  ww .  jav  a  2s  . c o m*/
        switch (target) {
        case ASIC:
            handleAsicRequest();
            return;
        case VERIFICATIONCONF:
            handleVerificationConfRequest();
            return;
        default:
            break;
        }
    } catch (CodedExceptionWithHttpStatus ex) {
        throw ex;
    } catch (CodedException ex) {
        throw new CodedExceptionWithHttpStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
    } catch (Exception ex) {
        throw new CodedExceptionWithHttpStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ErrorCodes.X_INTERNAL_ERROR, ex.getMessage());
    }
}

From source file:org.opendatakit.api.admin.UserAdminService.java

@ApiOperation(value = "Get information and roles for a single user by username.")
@GET/*from  w ww  . ja  v a2 s  .  c  o m*/
@Path("users/username:{username}")
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
public Response getUser(@PathParam("username") String username) {
    UserEntity resultUserEntity = null;
    try {

        RegisteredUsersTable user = RegisteredUsersTable.getUserByUsername(username,
                callingContext.getUserService(), callingContext.getDatastore());

        if (user == null) {
            return Response.status(Status.NOT_FOUND).entity("User not found.")
                    .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Credentials", "true").build();
        }
        UserSecurityInfo userSecurityInfo = new UserSecurityInfo(user.getUsername(), user.getFullName(),
                user.getEmail(), UserSecurityInfo.UserType.REGISTERED, user.getOfficeId());

        SecurityServiceUtil.setAuthenticationLists(userSecurityInfo, user.getUri(), callingContext);
        resultUserEntity = UserRoleUtils.getEntityFromUserSecurityInfo(userSecurityInfo);

    } 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(resultUserEntity).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:org.geogig.geoserver.rest.GeogigDispatcher.java

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

    try {//from  w  ww.  ja  v a 2 s .c  o  m
        converter.service(req, resp);
    } catch (Exception e) {
        if (e instanceof CommandSpecException) {
            String msg = e.getMessage();
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            if (msg != null) {
                resp.getOutputStream().write(msg.getBytes(Charsets.UTF_8));
            }
            return null;
        }
        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:com.fpmislata.banco.presentation.controladores.CuentaBancariaController.java

@RequestMapping(value = "/cuentabancaria/{idCuentaBancaria}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
public void update(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada, @PathVariable("idCuentaBancaria") int idCuentaBancaria) {
    try {//from w  ww .  j av a 2 s.  co  m
        CuentaBancaria cuentaBancaria = (CuentaBancaria) jsonTransformer.fromJsonToObject(jsonEntrada,
                CuentaBancaria.class);
        cuentaBancariaService.update(cuentaBancaria);
        String jsonSalida = jsonTransformer.ObjectToJson(cuentaBancaria);

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonSalida);

    } catch (BusinessException ex) {
        List<BusinessMessage> bussinessMessage = ex.getBusinessMessages();
        String jsonSalida = jsonTransformer.ObjectToJson(bussinessMessage);

        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(CuentaBancariaService.class.getName()).log(Level.SEVERE, null, ex1);
        }

    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(CuentaBancariaController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}

From source file:org.craftercms.cstudio.publishing.servlet.FileUploadServlet.java

/**
 * handle error case/*  ww w . j a  va 2  s.c  om*/
 * 
 * @param files
 * @param response
 * @param exception
 */
private void handleErrorCase(Map<String, InputStream> files, HttpServletResponse response,
        Exception exception) {
    if (LOGGER.isErrorEnabled()) {
        LOGGER.error("Failed to upload files.", exception);
    }
    closeAll(files);
    try {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage());
    } catch (IOException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Failed to upload files.", e);
        }
    }
}

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

@ApiOperation(value = "Get information about a particular office.", response = RegionalOffice.class)
@GET/* w w w  . j  av a  2s .  c o  m*/
@Path("{officeId}")
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
public Response getOffice(@PathParam("officeId") String officeId) {
    RegionalOffice office = null;
    try {
        OdkRegionalOfficeTable.assertRelation(callingContext);
        OdkRegionalOfficeTable record = OdkRegionalOfficeTable.getRecordFromDatabase(officeId, callingContext);
        if (record == null) {
            return Response.status(Status.NOT_FOUND).entity("Office ID not found.")
                    .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Credentials", "true").build();
        }
        office = new RegionalOffice(record.getUri(), record.getRegionalOfficeName(),
                record.getRegionalOfficeId());
    } catch (ODKDatastoreException | DatastoreFailureException 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(office).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:biz.taoconsulting.dominodav.methods.GET.java

/**
 * @see biz.taoconsulting.dominodav.methods.AbstractDAVMethod#action()
 *///from w  w  w  . j  ava 2 s.  co  m
public void action() {
    InputStream stream = null; // The input stream coming from the resource
    OutputStream out = null; // The Servlet Response
    HttpServletResponse res = this.getResp();

    try {
        // check if focused resource is a collection or a file resource...
        // collections are handled by propfind method
        // files / data will be send through the response stream writer...
        IDAVRepository rep = this.getRepository();
        // Resource-Path is stripped by the repository name!
        // String curPath = (String)
        // this.getHeaderValues().get("resource-path");
        // uri is the unique identifier on the host includes servlet and
        // repository but not server
        String curURI = (String) this.getHeaderValues().get("uri");
        IDAVResource resource = rep.getResource(curURI);

        // Not ideal for browser access: we get the resource twice
        if (resource.isCollection()) {
            // LOGGER.info("Resource "+curURI +" is a collection");
            PROPFIND p = new PROPFIND();
            // Transfer the context if any
            p.setContext(this.getContext());
            p.calledFromGET();
            // LOGGER.info("After Called from GET");
            p.process(this.getReq(), res, this.getRepository(), this.getLockManager());
            // LOGGER.info("After Process ");
        } else {
            // LOGGER.info("Resource "+curURI +" is NOT a collection");
            res.setHeader("Content-Type", resource.getMimeType());
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Expires", "0");
            res.setHeader("ETag", resource.getETag());

            // TODO: Do we need content-disposition attachment or should it
            // be inline?
            res.setHeader("Content-disposition",
                    "inline; filename*=" + ((IDAVAddressInformation) resource).getName());
            // LOGGER.info("Set header finnish");
            Long curLen = resource.getContentLength();
            if (curLen != null && curLen.longValue() > 0) {
                // LOGGER.info("CurrLen is not null and positive="+
                // curLen.toString());
                res.setHeader("Content-Length", resource.getContentLength().toString());
            } else {
                // LOGGER.info("CurrLen is null!!!");
            }
            // Get the stream of the resource object and copy it into
            // the outputstream which is provided by the response object

            try {
                // LOGGER.info("Before resource getStream; class="+resource.getClass().toString());
                stream = resource.getStream();

                int read = 0;
                byte[] bytes = new byte[32768]; // ToDo is 32k a good
                // buffer?

                int totalread = 0;

                // TODO: Improve on this - is there a better way from input
                // to output stream?
                out = this.getOutputStream();
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                    totalread += read;
                }

                // Capture the result length
                // LOGGER.info("Before resource setContentLength");
                res.setContentLength(totalread);
                // LOGGER.info("After resource setContentLength");

            } catch (IOException iox) {
                this.setErrorMessage("Get method failed with:" + iox.getMessage(),
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                LOGGER.error(iox);
            }

        }
    } catch (Exception exc) {
        LOGGER.error("Get method failed with:" + exc.getMessage(), exc);
        this.setErrorMessage("Get method failed with:" + exc.getMessage(), HttpServletResponse.SC_NOT_FOUND);
    } finally {
        // Close of all resources
        try {

            if (out != null) {
                out.flush();
                out.close();
            }

            if (stream != null) {
                stream.close();
            }

        } catch (Exception e) {
            LOGGER.error("GET Object cleanup failed:" + e.getMessage(), e);
        }
    }
}

From source file:org.apache.cxf.fediz.service.idp.kerberos.KerberosAuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (skipIfAlreadyAuthenticated) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth != null && existingAuth.isAuthenticated()
                && !(existingAuth instanceof AnonymousAuthenticationToken)) {
            chain.doFilter(request, response);
            return;
        }/*  ww w  .j  a v a  2  s  .com*/
    }
    String header = request.getHeader("Authorization");
    if ((header != null) && header.startsWith("Negotiate ")) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(10).getBytes("UTF-8");
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(authenticationRequest);
        } catch (AuthenticationException e) {
            //That shouldn't happen, as it is most likely a wrong
            //configuration on the server side
            logger.warn("Negotiate Header was invalid: " + header, e);
            SecurityContextHolder.clearContext();
            if (failureHandler != null) {
                failureHandler.onAuthenticationFailure(request, response, e);
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.flushBuffer();
            }
            return;
        }
        sessionStrategy.onAuthentication(authentication, request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        if (successHandler != null) {
            successHandler.onAuthenticationSuccess(request, response, authentication);
        }
    }
    chain.doFilter(request, response);
}

From source file:com.carolinarollergirls.scoreboard.jetty.XmlScoreBoardServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.doPost(request, response);

    try {/* w  w w  .jav  a2s.  c  om*/
        if ("/set".equals(request.getPathInfo()))
            set(request, response);
        else if (!response.isCommitted())
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (JDOMException jE) {
        ScoreBoardManager.printMessage("XmlScoreBoardServlet ERROR: " + jE.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}