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:eu.trentorise.smartcampus.mobility.controller.rest.CacheController.java

@RequestMapping(method = RequestMethod.GET, value = "/routesDB/{appId}", produces = "application/zip")
public @ResponseBody void getRoutesDB(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, @PathVariable String appId) {
    try {/*from  www . j  ava  2 s  .c o  m*/
        String dbId = getRoutesDB(appId);
        if (dbId == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"routesdb.zip\"");

        InputStream is = smartPlannerHelper.routesDB(dbId);

        ByteStreams.copy(is, response.getOutputStream());

    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:csiro.pidsvc.servlet.info.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *     response)//from   ww w.  ja  v a 2 s . co  m
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setDateHeader("Expires", 0);
    response.addHeader("Cache-Control",
            "no-cache,no-store,private,must-revalidate,max-stale=0,post-check=0,pre-check=0");

    String cmd = request.getParameter("cmd");
    if (cmd == null || cmd.isEmpty())
        return;

    ManagerJson mgr = null;
    JSONObject ret;
    try {
        Settings.init(this);
        mgr = new ManagerJson(request);

        response.setContentType("application/json");

        _logger.info("Processing \"{}\" command -> {}?{}", cmd, request.getRequestURL(),
                request.getQueryString());
        if (cmd.equalsIgnoreCase("search")) {
            int page = 1;
            String sPage = request.getParameter("page");
            if (sPage != null && sPage.matches("\\d+"))
                page = Integer.parseInt(sPage);

            ret = mgr.getMappings(page, request.getParameter("mapping"), request.getParameter("type"),
                    request.getParameter("creator"), Literals.toInt(request.getParameter("deprecated"), 0));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_pid_config")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            String mappingPath = request.getParameter("mapping_path");

            ret = mappingId > 0 ? mgr.getPidConfig(mappingId)
                    : (mappingId == 0 ? mgr.getPidConfig((String) null) : mgr.getPidConfig(mappingPath));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("check_mapping_path_exists")) {
            response.getWriter()
                    .write(mgr.checkMappingPathExists(request.getParameter("mapping_path")).toString());
        } else if (cmd.equalsIgnoreCase("search_parent")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            response.getWriter()
                    .write(mgr.searchParentMapping(mappingId, request.getParameter("q")).toString());
        } else if (cmd.equalsIgnoreCase("get_settings"))
            response.getWriter().write(mgr.getSettings().toString());
        else if (cmd.equalsIgnoreCase("search_condition_set")) {
            int page = 1;
            String sPage = request.getParameter("page");
            if (sPage != null && sPage.matches("\\d+"))
                page = Integer.parseInt(sPage);

            ret = mgr.getConditionSets(page, request.getParameter("q"));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_condition_set_config")) {
            String name = request.getParameter("name");
            ret = mgr.getConditionSetConfig(name);
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("search_lookup")) {
            int page = 1;
            String sPage = request.getParameter("page");
            if (sPage != null && sPage.matches("\\d+"))
                page = Integer.parseInt(sPage);

            ret = mgr.getLookups(page, request.getParameter("ns"));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_lookup_config")) {
            String ns = request.getParameter("ns");
            ret = mgr.getLookupConfig(ns);
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_manifest")) {
            response.getWriter().write(Settings.getInstance().getManifestJson().toString());
        } else if (cmd.equalsIgnoreCase("is_new_version_available")) {
            response.getWriter().write(Settings.getInstance().isNewVersionAvailableJson().toString());
        } else if (cmd.equalsIgnoreCase("global_js")) {
            response.setContentType("text/javascript");
            response.getWriter()
                    .write("var GlobalSettings = " + mgr.getGlobalSettings(request).toString() + ";");
        } else if (cmd.equalsIgnoreCase("chart")) {
            ret = mgr.getChart();
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_mapping_dependencies")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            String mappingPath = request.getParameter("mapping_path");
            String inputJson = request.getParameter("json");
            JSONObject jsonThis = (JSONObject) (new JSONParser()).parse(inputJson);

            if (mappingPath != null && mappingPath.isEmpty())
                mappingPath = null;
            if (jsonThis != null && jsonThis.isEmpty())
                jsonThis = null;
            ret = mgr.getMappingDependencies((Object) (jsonThis == null ? mappingId : jsonThis), mappingPath);
            response.getWriter()
                    .write(mappingId == -1 && jsonThis == null || ret == null ? "{}" : ret.toString());
        } else if (cmd.equalsIgnoreCase("echo")) {
            echo(request, response);
        }
    } catch (Exception e) {
        _logger.error(e);
        Http.returnErrorCode(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (mgr != null)
            mgr.close();
    }
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom GET by calling handler and writing results to response.
 *//* w w  w  . j  ava  2s  .c  o m*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isAtomServiceURI(areq)) {
                // return an Atom Service document
                AtomService service = handler.getAtomService(areq);
                Document doc = service.serviceToDocument();
                res.setContentType("application/atomsvc+xml; charset=utf-8");
                Writer writer = res.getWriter();
                XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(doc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCategoriesURI(areq)) {
                Categories cats = handler.getCategories(areq);
                res.setContentType("application/xml");
                Writer writer = res.getWriter();
                Document catsDoc = new Document();
                catsDoc.setRootElement(cats.categoriesToElement());
                XMLOutputter outputter = new XMLOutputter();
                outputter.output(catsDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCollectionURI(areq)) {
                // return a collection
                Feed col = handler.getCollection(areq);
                col.setFeedType(FEED_TYPE);
                WireFeedOutput wireFeedOutput = new WireFeedOutput();
                Document feedDoc = wireFeedOutput.outputJDom(col);
                res.setContentType("application/atom+xml; charset=utf-8");
                Writer writer = res.getWriter();
                XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(feedDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isEntryURI(areq)) {
                // return an entry
                Entry entry = handler.getEntry(areq);
                if (entry != null) {
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");
                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(entry, writer);
                    writer.close();
                } else {
                    res.setStatus(HttpServletResponse.SC_NOT_FOUND);
                }
            } else if (handler.isMediaEditURI(areq)) {
                AtomMediaResource entry = handler.getMediaResource(areq);
                res.setContentType(entry.getContentType());
                res.setContentLength((int) entry.getContentLength());
                Utilities.copyInputToOutput(entry.getInputStream(), res.getOutputStream());
                res.getOutputStream().flush();
                res.getOutputStream().close();
            } else {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing GET", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing GET", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:controller.TemasNivel2RestController.java

/**
*
* @param id//w  w  w . ja  va 2  s  .c  om
* @param request
* @param response
* @return JSON
*/

@RequestMapping(value = "/{id}/temasnivel3", method = RequestMethod.GET, produces = "application/json")
public String getMunicipiosJSON(@PathVariable("id") int id, HttpServletRequest request,
        HttpServletResponse response) {
    TemasNivel2DAO tabla = new TemasNivel2DAO();
    Gson JSON;
    List<TemasNivel3> lista;
    try {
        lista = tabla.selectAllTemasNivel3(id);
        if (lista.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existen elementos");
            JSON = new Gson();
            return JSON.toJson(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServer", ex.getMessage());
        JSON = new Gson();
        return JSON.toJson(e);
    }

    Datos<TemasNivel3> datos = new Datos<>();
    datos.setDatos(lista);
    JSON = new Gson();
    response.setStatus(HttpServletResponse.SC_OK);
    return JSON.toJson(datos);
}

From source file:it.cnr.icar.eric.server.interfaces.rest.RestServlet.java

/** Handles the HTTP <code>GET</code> method.
 * @param request servlet request/*w ww.  j av a  2 s.c o m*/
 * @param response servlet response
 */
@SuppressWarnings("static-access")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String interfase = request.getParameter("interface");

    try {
        if ((interfase == null) || interfase.equals("")) {
            //First check if it is a user defined URL since that is less expensive to match        
            UserDefinedURLHandler udefURLHandler = new UserDefinedURLHandler(request, response);
            try {
                udefURLHandler.processGetRequest();
                response.setStatus(response.SC_OK);
            } catch (ObjectNotFoundException e) {
                FilePathURLHandler filePathURLHandler = new FilePathURLHandler(request, response);
                filePathURLHandler.processGetRequest();
                response.setStatus(response.SC_OK);
            }
        } else if (interfase.equalsIgnoreCase("QueryManager")) {
            QueryManagerURLHandler qmURLHandler = new QueryManagerURLHandler(request, response);
            qmURLHandler.processGetRequest();
            response.setStatus(response.SC_OK);
        } else if (interfase.equalsIgnoreCase("LifeCycleManager")) {
            LifeCycleManagerURLHandler lcmURLHandler = new LifeCycleManagerURLHandler(request, response);
            lcmURLHandler.processGetRequest();
            response.setStatus(response.SC_OK);
        } else if (extendedInterfaces.containsKey(interfase)) {
            String className = extendedInterfaces.get(interfase).toString();
            URLHandler handler = createURLHandlerInstance(className, request, response);
            if (handler != null) {
                handler.processGetRequest();
                response.setStatus(response.SC_OK);
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Invalid request. Unknown interface: " + interfase);
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Invalid request. Unknown interface: " + interfase);
        }
    } catch (ObjectNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (InvalidRequestException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (UnimplementedException e) {
        response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, e.getMessage());
    } catch (RegistryException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:controller.TemasNivel1RestController.java

/**
*
* @param id//from   w  w  w  .j  a  va2  s  . co  m
* @param request
* @param response
* @return JSON
*/

@RequestMapping(value = "/{id}/temasnivel2", method = RequestMethod.GET, produces = "application/json")
public String getMunicipiosJSON(@PathVariable("id") int id, HttpServletRequest request,
        HttpServletResponse response) {
    TemasNivel1DAO tabla = new TemasNivel1DAO();
    Gson JSON;
    List<TemasNivel2> lista;
    try {
        lista = tabla.selectAllTemasNivel2(id);
        if (lista.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existen elementos");
            JSON = new Gson();
            return JSON.toJson(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServer", ex.getMessage());
        JSON = new Gson();
        return JSON.toJson(e);
    }

    Datos<TemasNivel2> datos = new Datos<>();
    datos.setDatos(lista);
    JSON = new Gson();
    response.setStatus(HttpServletResponse.SC_OK);
    return JSON.toJson(datos);
}

From source file:org.opendatakit.api.forms.FormService.java

@POST
@ApiOperation(value = "Upload a zipped form definition as multipart/form-data.", response = FormUploadResult.class)
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
@Path("{appId}/{odkClientVersion}")
public Response doPost(@Context HttpServletRequest req, @Context HttpServletResponse resp,
        @PathParam("odkClientVersion") String odkClientVersion, @PathParam("appId") String appId,
        @Context UriInfo info) throws IOException {
    logger.debug("Uploading...");
    ServiceUtils.examineRequest(req.getServletContext(), req);

    req.getContentLength();//from   w  w w .j av  a 2  s. c  o m
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new WebApplicationException(ErrorConsts.NO_MULTI_PART_CONTENT,
                HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        TablesUserPermissions userPermissions = ContextUtils.getTablesUserPermissions(callingContext);
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
        Map<String, byte[]> files = null;
        String tableId = null;
        List<String> regionalOffices = new ArrayList<>();

        // unzipping files

        for (FileItem item : items) {

            // Retrieve all Regional Office IDs to which a form definition
            // is going to be assigned to
            if (item.getFieldName().equals(WebConsts.OFFICE_ID)) {
                regionalOffices.add(item.getString());
            }

            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());

            if (fieldName.equals(WebConsts.ZIP_FILE)) {
                if (fileName == null || !(fileName.endsWith(".zip"))) {
                    throw new WebApplicationException(ErrorConsts.NO_ZIP_FILE,
                            HttpServletResponse.SC_BAD_REQUEST);
                }

                InputStream fileStream = item.getInputStream();
                ZipInputStream zipStream = new ZipInputStream(fileStream);
                files = processZipInputStream(zipStream);
            }
        }

        tableId = getTableIdFromFiles(files);

        FormUploadResult formUploadResult = uploadFiles(odkClientVersion, appId, tableId, userPermissions,
                files, regionalOffices);

        FileManifestManager manifestManager = new FileManifestManager(appId, odkClientVersion, callingContext);
        OdkTablesFileManifest manifest = manifestManager.getManifestForTable(tableId);
        FileManifestService.fixDownloadUrls(info, appId, odkClientVersion, manifest);

        formUploadResult.setManifest(manifest);
        String eTag = Integer.toHexString(manifest.hashCode()); // Is this
                                                                // right?

        return Response.status(Status.CREATED).entity(formUploadResult).header(HttpHeaders.ETAG, eTag)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();

    } catch (FileUploadException | ODKDatastoreException | ODKTaskLockException | PermissionDeniedException
            | TableAlreadyExistsException e) {
        logger.error("Error uploading zip", e);
        throw new WebApplicationException(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString(),
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    }
}

From source file:de.mpg.mpdl.service.rest.screenshot.service.HtmlScreenshotServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from   w  ww  .j  a v a 2  s  .  c o m*/
        if (ServletFileUpload.isMultipartContent(req)) {
            file = screenshotService.takeScreenshot(getUploadedFiles(req));
        } else {
            File html = File.createTempFile("htmlScreenshot", ".html");
            if (req.getParameter("html") != null) {
                IOUtils.write(req.getParameter("html").getBytes(), new FileOutputStream(html));
            } else {
                IOUtils.copy(req.getInputStream(), new FileOutputStream(html));
            }
            System.out.println(html.getAbsolutePath());
            // TO Do After the copy the of the files
            browserWidth = (readBrowserParam(req, "browserWidth") != "")
                    ? Integer.parseInt(req.getParameter("browserWidth"))
                    : HtmlScreenshotService.DEFAULT_WIDTH;
            browserHeight = (readBrowserParam(req, "browserHeight") != "")
                    ? Integer.parseInt(req.getParameter("browserHeight"))
                    : HtmlScreenshotService.DEFAULT_HEIGHT;
            useFireFox = (readBrowserParam(req, "useFireFox") != "")
                    ? Boolean.parseBoolean(req.getParameter("useFireFox"))
                    : false;

            file = screenshotService.takeScreenshot(html, browserWidth, browserHeight, useFireFox);
            if (transformScreenshot(req)) {
                imageTransformer.transform(file, resp.getOutputStream(), readParam(req, "format"),
                        readParam(req, "size"), readParam(req, "crop"), readParam(req, "priority"),
                        readParam(req, "params1"), readParam(req, "params2"));
            } else
                IOUtils.copy(new FileInputStream(file), resp.getOutputStream());
        }
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        e.printStackTrace();
    }
}

From source file:it.unitn.disi.smatch.webapi.server.controllers.AbstractController.java

@ResponseBody
@ExceptionHandler(IOException.class)
protected JSONObject handleIOException(IOException e) throws JSONException {
    logger.error(e.getMessage(), e);// www  .  ja  v  a 2  s. com
    return prepareErrorResponse(e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}