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.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void post(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/*w  ww.j  a  v a 2s.  co  m*/
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());

        if (!object.has("pairingCode") || object.isNull("pairingCode")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        String code = object.getString("pairingCode");

        if (code.equalsIgnoreCase("null")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        Location location = Location.findForPairing(code);

        if (location == null) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PAIRING_CODE,
                    "Invalid pairing code; pairing did not occur");
        }
        String relayName;

        if (object.has("name") && !object.isNull("name")) {
            relayName = object.getString("name");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA,
                    "Missing relay name from JSON");
        }
        ControllerRelay relay = location.pair(code, relayName);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.PAIRING_FAILURE,
                    "Pairing failed due to an invalid pairing code or expired pairing code");
        }
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("apiKeyId", relay.getControllerRelayId());
        json.put("apiKeySecret", Configuration.decrypt(location.getLocationId(), relay.getApiKeySecret()));
        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.getWriter().println((new JSONObject(json)).toString());
        resp.getWriter().flush();
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

From source file:eionet.web.action.SchemasJsonApiActionBean.java

/**
 * Returns information on released/public schemas associated with the given obligation in DD. Both generated schemas (e.g.
 * http://dd.eionet.europa.eu/GetSchema?id=TBL8286) and manually uploaded schemas (e.g.
 * http://dd.eionet.europa.eu/schemas/fgases/FGasesReporting.xsd) are to be included in the response.
 *
 * The response of the method is to be sent as JSON objects (application/json) representing each schema. Every object shall have
 * the following attributes: url identifier (for generated schemas it's the table's Identifier) name (for generated schemas it's
 * the table's Short name). status - Dataset/Schemaset status eg. Released, Recorded or Public draft.
 *
 * If no schemas are found for the requested obligation ID, the method shall return HTTP 404.
 *
 * Parameters: obligationId - Obligation Identifier. Eg, ROD URL: http://rod.eionet.europa.eu/obligations/28 releasedOnly - if
 * true, then returns only released schemas. Otherwise all public schemas will be returned
 *
 * @return Stripes StreamingResolution or ErrorResolution
 *///from   w  ww. ja  va  2  s .c o  m
@HandlesEvent("forObligation")
public Resolution getSchemasForObligation() {

    if (StringUtils.isEmpty(obligationId)) {
        return new ErrorResolution(HttpServletResponse.SC_BAD_REQUEST, "Missing obligationId parameter.");
    }
    List<DataSetTable> datasetTables;
    List<Schema> schemas;
    try {
        datasetTables = tableService.getTablesForObligation(obligationId, releasedOnly);
        schemas = schemaService.getSchemasForObligation(obligationId, releasedOnly);

        if (CollectionUtils.isNotEmpty(datasetTables) || CollectionUtils.isNotEmpty(schemas)) {
            String jsonResult = convertToJson(datasetTables, schemas);
            return new StreamingResolution("application/json", jsonResult);
        } else {
            return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND,
                    "Schemas not found for this obligation.");
        }

    } catch (ServiceException e) {
        e.printStackTrace();
        return new ErrorResolution(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "System error occurred.");
    }
}

From source file:cz.muni.fi.pa165.deliverysystemweb.CourierActionBean.java

public Resolution delete() {
    String id = getContext().getRequest().getParameter("id");

    Long l_id;/*from www. j  a  va2  s. c  o  m*/
    try {
        l_id = Long.valueOf(id);
    } catch (NumberFormatException ex) {
        return new ErrorResolution(HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        courierDTO = courierService.findCourier(l_id);
    } catch (DataAccessException ex) {
        return new ErrorResolution(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (courierDTO == null) {
        return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND);
    }

    try {
        courierService.deleteCourier(courierDTO);
    } catch (DataAccessException ex) {
        return new ErrorResolution(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return new RedirectResolution(this.getClass(), "list");
}

From source file:jp.or.openid.eiwg.scim.operation.Operation.java

/**
 * ??//from w  w  w .  j  a v a  2s.c o m
 *
 * @param context 
 * @param request 
 */
public boolean Authentication(ServletContext context, HttpServletRequest request) throws IOException {
    boolean result = false;

    // Authorization?
    String authorization = request.getHeader("Authorization");

    if (authorization == null || StringUtils.isEmpty(authorization)) {
        // 
        setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_UNAUTHORIZED);
        //return false;
        return true;
    }

    String[] values = authorization.split(" ");

    // ?
    setError(0, null, null);

    if (values.length < 2) {
        // 
        setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_UNAUTHORIZED);
    } else {
        // ????????
        if ("Basic".equalsIgnoreCase(values[0])) {
            // HTTP Basic ?
            String userID;
            String password;
            String[] loginInfo = SCIMUtil.decodeBase64(values[1]).split(":");

            if (loginInfo.length < 2) {
                // 
                setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS);
            } else {
                // ??
                userID = loginInfo[0];
                // 
                password = loginInfo[1];

                if (StringUtils.isEmpty(userID) || StringUtils.isEmpty(password)) {
                    // 
                    setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                            MessageConstants.ERROR_INVALID_CREDENTIALS);
                } else {
                    // ????

                    // ???
                    ObjectMapper mapper = new ObjectMapper();
                    ArrayList<LinkedHashMap<String, Object>> adminInfoList = null;
                    try {
                        adminInfoList = mapper.readValue(new File(context.getRealPath("/WEB-INF/Admin.json")),
                                new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() {
                                });
                    } catch (IOException e) {
                        // 
                        setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null,
                                MessageConstants.ERROR_UNKNOWN);
                        e.printStackTrace();
                        return result;
                    }

                    if (adminInfoList != null && !adminInfoList.isEmpty()) {
                        Iterator<LinkedHashMap<String, Object>> adminInfoIt = adminInfoList.iterator();
                        while (adminInfoIt.hasNext()) {
                            LinkedHashMap<String, Object> adminInfo = adminInfoIt.next();
                            Object adminID = SCIMUtil.getAttribute(adminInfo, "id");
                            Object adminPassword = SCIMUtil.getAttribute(adminInfo, "password");
                            // id????
                            if (adminID != null && adminID instanceof String) {
                                if (userID.equals(adminID.toString())) {
                                    // password????
                                    if (adminID != null && adminID instanceof String) {
                                        if (password.equals(adminPassword.toString())) {
                                            // ??
                                            result = true;
                                        }
                                    }

                                    break;
                                }
                            }
                        }

                        if (result != true) {
                            // 
                            setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                                    MessageConstants.ERROR_INVALID_CREDENTIALS);
                        }
                    } else {
                        // 
                        setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                                MessageConstants.ERROR_INVALID_CREDENTIALS);
                    }
                }
            }
        } else if ("Bearer".equalsIgnoreCase(values[0])) {
            // OAuth2 Bearer 
            String token = values[1];

            if (StringUtils.isEmpty(token)) {
                // 
                setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS);
            } else {
                // ??

                // ???
                ObjectMapper mapper = new ObjectMapper();
                ArrayList<LinkedHashMap<String, Object>> adminInfoList = null;
                try {
                    adminInfoList = mapper.readValue(new File(context.getRealPath("/WEB-INF/Admin.json")),
                            new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() {
                            });
                } catch (IOException e) {
                    // 
                    setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null,
                            MessageConstants.ERROR_UNKNOWN);
                    e.printStackTrace();
                    return result;
                }

                if (adminInfoList != null && !adminInfoList.isEmpty()) {
                    Iterator<LinkedHashMap<String, Object>> adminInfoIt = adminInfoList.iterator();
                    while (adminInfoIt.hasNext()) {
                        LinkedHashMap<String, Object> adminInfo = adminInfoIt.next();
                        Object adminToken = SCIMUtil.getAttribute(adminInfo, "bearer");
                        // token????
                        if (adminToken != null && adminToken instanceof String) {
                            if (token.equals(adminToken.toString())) {
                                // ??
                                result = true;

                                break;
                            }
                        }
                    }

                    if (result != true) {
                        // 
                        setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                                MessageConstants.ERROR_INVALID_CREDENTIALS);
                    }
                } else {
                    // 
                    setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                            MessageConstants.ERROR_INVALID_CREDENTIALS);
                }
            }
        } else {
            // 
            setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS);
        }
    }

    return result;
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.BasicProfileController.java

@RequestMapping(method = RequestMethod.GET, value = "/basicprofile/profiles")
public @ResponseBody BasicProfiles findProfiles(HttpServletResponse response,
        @RequestParam List<String> userIds) {
    try {/*from  w  ww.ja v  a  2s  . c o m*/
        BasicProfiles profiles = new BasicProfiles();
        profiles.setProfiles(profileManager.getUsers(userIds));
        return profiles;
    } catch (Exception e) {
        logger.error(e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:com.fpmislata.banco.presentation.controladores.EntidadBancariaController.java

@RequestMapping(value = {
        "/entidadbancaria" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada) {
    try {//from   www .j a v  a 2s.  c om
        EntidadBancaria entidadBancaria = (EntidadBancaria) jsonTransformer.fromJsonToObject(jsonEntrada,
                EntidadBancaria.class);
        entidadBancariaService.insert(entidadBancaria);

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

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

        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo Lista de Mensajes", ex1);
        }
    } catch (Exception ex1) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex1.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex2) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo la traza", ex2);
        }
    }
}

From source file:com.adobe.acs.commons.oak.impl.EnsureOakIndexServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String forceParam = StringUtils.defaultIfEmpty(request.getParameter(PARAM_FORCE), "false");
    boolean force = Boolean.parseBoolean(forceParam);

    String path = StringUtils.stripToNull(request.getParameter(PARAM_PATH));
    try {/*from ww w  . j  a  v  a2  s .c o m*/

        int count = 0;
        if (StringUtils.isBlank(path)) {
            count = ensureOakIndexManager.ensureAll(force);
        } else {
            count = ensureOakIndexManager.ensure(force, path);
        }

        response.setContentType("text/plain; charset=utf-8");
        response.getWriter().println("Initiated the ensuring of " + count + " oak indexes");
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
        log.warn("Caught IOException while handling doPost() in the Ensure Oak Index Servlet", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java

/**
 * Handles the HTTP/*  w  w  w  .ja  va 2s .c o m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);

    if (isMultiPart) {
        log("Content-Type: " + request.getContentType());
        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

        List items = null;

        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        ListIterator li = items.listIterator();

        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                if (debug) {
                    processFormField(fileItem);
                }
            } else {
                writer.print(processUploadedFile(fileItem));
            }
        }
    }

    if ("application/octet-stream".equals(request.getContentType())) {
        log("Content-Type: " + request.getContentType());
        String filename = request.getHeader("X-File-Name");

        try {
            is = request.getInputStream();
            fos = new FileOutputStream(new File(realPath + filename));
            IOUtils.copy(is, fos);
            response.setStatus(HttpServletResponse.SC_OK);
            writer.print("{success: true}");
        } catch (FileNotFoundException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }

        writer.flush();
        writer.close();
    }
}

From source file:controller.IndicadoresMontoRestController.java

@RequestMapping(value = "/{idi}/municipios/{idm}", method = RequestMethod.GET, produces = "application/xml")
public String getXML(@PathVariable("idi") String idi, @PathVariable("idm") int idm, HttpServletRequest request,
        HttpServletResponse response) {/*from   www  .  ja  va2s .c  om*/

    XStream XML = new XStream();
    List<DatosRegistrosIdMunicipio> listaFinal;
    List<Registros> listaRegistros;
    RegistrosDAO tablaRegistros;
    tablaRegistros = new RegistrosDAO();
    /*
    *obtenemos la lista Registros
    */
    try {
        listaRegistros = tablaRegistros.selectAllResgistrosByIdIndicadorAndMunicipio(idi, idm);
        if (listaRegistros.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning",
                    "No existen registros del indicador:" + idi + " asociados al municipio con id:" + idm);
            XML.alias("message", Error.class);
            return XML.toXML(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServer", ex.getMessage());
        XML.alias("message", Error.class);
        return XML.toXML(e);
    }
    listaFinal = new ArrayList<>();
    for (Registros r : listaRegistros) {
        listaFinal.add(new DatosRegistrosIdMunicipio(r.getIdRegistros(), r.getAnio(), r.getCantidad()));
    }

    response.setStatus(HttpServletResponse.SC_OK);
    XML.alias("registro", DatosRegistrosIdMunicipio.class);
    return XML.toXML(listaFinal);
}

From source file:com.google.nigori.server.NigoriServlet.java

private String getJsonAsString(HttpServletRequest req, int maxLength) throws ServletException {

    if (maxLength != 0 && req.getContentLength() > maxLength) {
        return null;
    }//from   w  ww.ja v  a 2s. c om

    String charsetName = req.getCharacterEncoding();
    if (charsetName == null) {
        charsetName = MessageLibrary.CHARSET;
    }

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream(), charsetName));
        StringBuilder json = new StringBuilder();
        char[] buffer = new char[64 * 1024];
        int charsRemaining = maxJsonQueryLength;
        int charsRead;
        while ((charsRead = in.read(buffer)) != -1) {
            charsRemaining -= charsRead;
            if (charsRemaining < 0) {
                throw new ServletException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                        "Json request exceeds server maximum length of " + maxLength);
            }
            json.append(buffer, 0, charsRead);
        }
        return json.toString();
    } catch (IOException ioe) {
        throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Internal error receiving data from client.");
    }
}