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:nl.dtls.fairdatapoint.api.controller.utils.HttpHeadersUtils.java

/**
 * Set response header for the internal server errors
 * //from   w  w w.  j  a va 2 s.c o  m
 * @param response  Http response
 * @param ex    Server exception
 * @return returns null (as a response body)
 */
public static String set500ResponseHeaders(HttpServletResponse response, Exception ex) {
    String errorMessage = ("Internal server error; Error message : " + ex.getMessage());
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    try {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage);
    } catch (IOException ex1) {
        LOGGER.warn(
                "Error setting error message for internal server " + "error; The error : " + ex1.getMessage());
    }
    response.setContentType(MediaType.TEXT_PLAIN_VALUE);
    return null;
}

From source file:com.sixt.service.framework.json.JsonUtil.java

public static JsonRpcResponse parseJsonRpcResponse(String rawResponse) {
    JsonParser parser = new JsonParser();
    JsonObject response = parser.parse(rawResponse).getAsJsonObject();
    JsonElement id = response.get("id");
    JsonElement errorElement = response.get("error");
    int responseStatus = HttpServletResponse.SC_OK;
    String error;// w  w  w. j a v a2  s . com
    if (!(errorElement instanceof JsonNull)) {
        if (errorElement instanceof JsonObject) {
            error = errorElement.toString();
            // try parsing it into RpcCallException to get the HttpStatus from there
            RpcCallException rpcEx = RpcCallException.fromJson(error);
            if (rpcEx != null) {
                responseStatus = rpcEx.getCategory().getHttpStatus();
                JsonElement resultElement = response.get("result");
                return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement,
                        errorElement, responseStatus);
            }
        }
        error = errorElement.getAsString();
        if (StringUtils.isNotBlank(error)) {
            responseStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
    }

    JsonElement resultElement = response.get("result");
    return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement, errorElement,
            responseStatus);
}

From source file:fr.epsi.controllers.rest.ProductController.java

@RequestMapping(value = "/product/{reference}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Product order(@PathVariable("reference") String reference, HttpServletResponse resp) {

    try {//from   w w w. java 2s. c  o m
        Products productModel = Products.getInstance();

        // On recupere le produit par reference
        Product product = productModel.findByRef(reference);

        if (product != null) {
            return product;
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
        return null;
    } catch (Exception e) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:se.acrend.christopher.server.web.control.BillingController.java

@RequestMapping(value = "/billing/getSubscription")
public void getSubscription(final HttpServletResponse response) throws IOException {
    try {/*from ww w.  j a v a  2 s.  c  o m*/
        SubscriptionInfo result = billingService.getSubscription();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        Gson gson = ParserFactory.createParser();
        gson.toJson(result, response.getWriter());
    } catch (Exception e) {
        log.error("Kunde inte hmta prenumeration.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.ss.Controller.T4uApproveRefundServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww  w.j  a va2 s  . c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    T4uUser user = (T4uUser) session.getAttribute(T4uConstants.T4uUser);
    if (!user.getUserGroup().equals("officer")) // Not authorised, only user himself can cancel order
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not authorised");
    else
        try {
            long orderId = Long.parseLong(request.getParameter("orderId"));
            T4uOrder order = T4uOrderDAO.getOrderById(orderId);
            if (order.getOrderStatus() == 2) { // Current status is Pending
                T4uOrderDAO.changeOrderStatus(orderId, 3, user);
                T4uOrder t4uOrder = new T4uOrder();
                t4uOrder.setOrderId(orderId);
                String json = new Gson().toJson(t4uOrder);
                response.setContentType("application/json");
                // Get the printwriter object from response to write the required json object to the output stream      
                PrintWriter out = response.getWriter();
                // Assuming your json object is **jsonObject**, perform the following, it will return your json object  
                out.print(json);
                out.flush();
            } else // Not pending status
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad order status");
        } catch (NumberFormatException ex) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "NumberFormatException");
        }
}

From source file:com.hp.autonomy.frontend.find.idol.web.IdolGlobalExceptionHandler.java

@ExceptionHandler(AciErrorException.class)
@ResponseBody//  w  w  w  .j a  va  2s.c om
public ErrorResponse authenticationFailedHandler(final AciErrorException exception,
        final HttpServletResponse response) {
    if (SECURITY_INFO_TOKEN_EXPIRED_ID.equals(exception.getErrorId())) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return new ErrorResponse("Security Info has expired");
    }

    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return handler(exception);
}

From source file:com.intbit.util.ServletUtil.java

public static void printInternalException(HttpServletResponse response, String errorMsg) throws IOException {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    Map<String, Object> errorMap = new HashMap<>();
    errorMap.put("error", errorMsg);
    response.getWriter().write(AppConstants.GSON.toJson(errorMap));
    response.getWriter().flush();/*from ww  w.  j  a v a  2s. co m*/

}

From source file:com.baidu.stqa.signet.web.common.exception.ExceptionResolver.java

@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    Object errors = null;/*from   w w w  .j a  v a2 s  . c  om*/

    if (ex instanceof MethodArgumentNotValidException) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        errors = getDecorateErrors(ex);
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errors = ex.getMessage();
        LOGGER.error(ex);
    }

    ObjectMapper mapper = new ObjectMapper();
    String errorJson = "Error occur when covert object to json!";
    try {
        errorJson = mapper.writeValueAsString(errors);
    } catch (Exception e) {
        e.printStackTrace();
    }

    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        outputStream.write(errorJson.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:byps.http.HWriteResponseHelper.java

public void writeResponse(ByteBuffer obuf, Throwable e, HttpServletResponse resp, boolean isAsync)
        throws IOException {
    if (log.isDebugEnabled())
        log.debug("writeResponse(" + obuf + ", exception=" + e + ", resp=" + resp);

    if (resp == null) {
        if (log.isDebugEnabled())
            log.debug(")writeResponse timeout");
        return; // timeout
    }//from   ww  w  .j a v a2 s. com

    if (listener != null) {
        if (log.isDebugEnabled())
            log.debug("call onBefore-listener");
        if (listener.onBeforeWriteHttpResponse(obuf, e, resp, isAsync)) {
            if (log.isDebugEnabled())
                log.debug(")writeResponse, onBefore-listener has written the response.");
        }
    }

    if (e != null) {

        int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        if (e instanceof BException) {
            BException bex = (BException) e;
            if (bex.code == BExceptionC.CANCELLED) {
                status = HttpServletResponse.SC_NOT_ACCEPTABLE;
            } else if (bex.code == BExceptionC.RESEND_LONG_POLL) {
                status = HttpServletResponse.SC_NO_CONTENT;
            }
        }

        if (status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            log.warn("Responding server error.", e);
        }

        resp.setStatus(status);

        PrintWriter wr = resp.getWriter();
        String errmsg = e.toString(); // (e instanceof BException) ?
                                      // ((BException)e).msg : e.toString();
        wr.print(errmsg);
        wr.close();

    } else {

        if (log.isDebugEnabled())
            log.debug("copy to servlet output");
        boolean isJson = BMessageHeader.detectProtocol(obuf) == BMessageHeader.MAGIC_JSON;
        resp.setContentType(isJson ? "application/json; charset=UTF-8" : "application/byps");
        resp.setContentLength(obuf.remaining());
        OutputStream os = resp.getOutputStream();

        if (log.isDebugEnabled()) {
            log.debug("buffer: \r\n" + BBuffer.toDetailString(obuf));
        }

        if (isAsync) {

            // Tomcat does not throw an IOException in asynchronous requests, if the
            // client
            // has closed the socket. Somewhere on stackoverflow.com I found a hack
            // to workaround this bug. The workaround splits the message into two
            // parts and calls flush() after each part. The second flush throws the
            // expected exception. But the author of this workaround mentioned, that
            // it does not work in all cases - and I confirm to him.
            // http://stackoverflow.com/questions/7124508/how-to-properly-detect-a-client-disconnect-in-servlet-spec-3
            int pos = obuf.position(), len = obuf.remaining() / 2;
            os.write(obuf.array(), pos, len);
            os.flush();
            os.write(obuf.array(), pos + len, obuf.remaining() - len);
            os.flush();
        } else {
            os.write(obuf.array(), obuf.position(), obuf.remaining());
        }

        os.close();

        if (listener != null) {
            if (log.isDebugEnabled())
                log.debug("call onAfter-listener");
            listener.onAfterWriteHttpResponse(obuf.remaining());
        }

    }
    if (log.isDebugEnabled())
        log.debug(")writeResponse");
}

From source file:fr.epsi.controllers.rest.LoginController.java

/**
 * Methode qui permet de connecter un utilisateur
 * @param username le username de l'utilisateur
 * @param password le password de l'utilisateur
 * @return Un message statut de la connexion
 *///from www .  j  a va 2s .c  o m
@RequestMapping(value = "/connect", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody User connect(@RequestParam("username") String username,
        @RequestParam("password") String password, HttpServletResponse resp) {

    try {
        Users userModel = Users.getInstance();
        //On recuoere le user
        User user = userModel.findByUsername(username);

        // On retourne le guuid de l'utilisateur
        if (user.getPassword().equals(password)) {
            user.generateGUID();
            return user;
        }

        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;

    } catch (Exception e) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}