Example usage for javax.servlet.http HttpServletResponse SC_NOT_FOUND

List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_FOUND

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_NOT_FOUND.

Prototype

int SC_NOT_FOUND

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_FOUND.

Click Source Link

Document

Status code (404) indicating that the requested resource is not available.

Usage

From source file:fi.hoski.web.forms.KeyInfoServlet.java

/**
 * Handles the HTTP/* w w w. ja  v a2 s . c  o m*/
 * <code>GET</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 doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        response.setHeader("Cache-Control", "no-cache"); // input comes from referrer
        response.setContentType("application/json");
        boolean authenticated = request.isUserInRole("member");

        JSONObject json = new JSONObject();
        Key parent = getAncestor(request);
        if (parent != null) {
            KeyInfo keyInfo = new KeyInfo(entities, events, races, "", parent, authenticated);
            Map<String, Object> m = keyInfo.getMap();
            String clubDiscount = (String) m.get("RaceSeries.ClubDiscount");
            String club = (String) m.get("Club");
            if (Boolean.parseBoolean(clubDiscount) && "HSK".equalsIgnoreCase(club)) {
                m.put("isClubDiscountGranted", true);
            } else {
                m.put("isClubDiscountGranted", false);
            }
            for (Map.Entry<String, Object> e : m.entrySet()) {
                if (e.getValue() instanceof List) {
                    JSONArray a = new JSONArray();
                    json.put(e.getKey(), a);
                    List<String> l = (List<String>) e.getValue();
                    for (String s : l) {
                        a.put(s);
                    }
                } else {
                    if (e.getValue() instanceof char[]) {
                        JSONArray a = new JSONArray();
                        json.put(e.getKey(), a);
                        char[] ar = (char[]) e.getValue();
                        for (char c : ar) {
                            a.put((int) c);
                        }
                    } else {
                        json.put(e.getKey(), e.getValue());
                    }
                }
            }
            json.write(response.getWriter());
        }
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        throw new ServletException(ex);
    }
}

From source file:edu.uci.ics.hyracks.control.cc.web.ApplicationInstallationHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {//  w w w  .  j a  v a 2s.  co  m
        while (target.startsWith("/")) {
            target = target.substring(1);
        }
        while (target.endsWith("/")) {
            target = target.substring(0, target.length() - 1);
        }
        String[] parts = target.split("/");
        if (parts.length != 1) {
            return;
        }
        final String[] params = parts[0].split("&");
        String deployIdString = params[0];
        String rootDir = ccs.getServerContext().getBaseDir().toString();
        final String deploymentDir = rootDir.endsWith(File.separator)
                ? rootDir + "applications/" + deployIdString
                : rootDir + File.separator + "/applications/" + File.separator + deployIdString;
        if (HttpMethods.PUT.equals(request.getMethod())) {
            class OutputStreamGetter extends SynchronizableWork {
                private OutputStream os;

                @Override
                protected void doRun() throws Exception {
                    FileUtils.forceMkdir(new File(deploymentDir));
                    String fileName = params[1];
                    File jarFile = new File(deploymentDir, fileName);
                    os = new FileOutputStream(jarFile);
                }
            }
            OutputStreamGetter r = new OutputStreamGetter();
            try {
                ccs.getWorkQueue().scheduleAndSync(r);
            } catch (Exception e) {
                throw new IOException(e);
            }
            try {
                IOUtils.copyLarge(request.getInputStream(), r.os);
            } finally {
                r.os.close();
            }
        } else if (HttpMethods.GET.equals(request.getMethod())) {
            class InputStreamGetter extends SynchronizableWork {
                private InputStream is;

                @Override
                protected void doRun() throws Exception {
                    String fileName = params[1];
                    File jarFile = new File(deploymentDir, fileName);
                    is = new FileInputStream(jarFile);
                }
            }
            InputStreamGetter r = new InputStreamGetter();
            try {
                ccs.getWorkQueue().scheduleAndSync(r);
            } catch (Exception e) {
                throw new IOException(e);
            }
            if (r.is == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            } else {
                response.setContentType("application/octet-stream");
                response.setStatus(HttpServletResponse.SC_OK);
                try {
                    IOUtils.copyLarge(r.is, response.getOutputStream());
                } finally {
                    r.is.close();
                }
            }
        }
        baseRequest.setHandled(true);
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.formtek.dashlets.sitetaskmgr.SiteWFUtil.java

/**
 * Retrieve the workflow path for the specified workflow
 * @param WorkflowPath wfPath/*from   w  w w .  ja  va  2 s . c  o  m*/
 * @param workflowService workflowService
 * @return WorkflowTask workflowTask
 */
public static WorkflowTask getWorkflowTask(WorkflowPath wfPath, WorkflowService workflowService) {
    logger.debug("Getting the workflow task");
    List<WorkflowTask> wfTasks = workflowService.getTasksForWorkflowPath(wfPath.getId());
    if (wfTasks == null || wfTasks.size() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND,
                "Failed to find workflow tasks for workflow instance id: " + wfPath.getInstance().getId());
    }
    // Get the last or the most current task
    WorkflowTask workflowTask = wfTasks.get(wfTasks.size() - 1);
    logger.debug("Retrieved WorkflowTask with id: " + workflowTask.getId());

    return workflowTask;
}

From source file:org.magnum.mobilecloud.video.VideoSvcCtrl.java

@PreAuthorize("hasRole(USER)")
@RequestMapping(method = RequestMethod.POST, value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike")
public @ResponseBody void unlikeVideo(@PathVariable("id") long id, Principal principal,
        HttpServletResponse response) {/*from w w  w.  j  av  a2  s.c  o m*/
    Video v = videoRepo.findOne(id);
    if (v != null) {
        HashSet<String> likers = v.getLikers();
        if (likers.contains(principal.getName())) {
            likers.remove(principal.getName());
            videoRepo.save(v);
            response.setStatus(HttpServletResponse.SC_OK);
        } else
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:de.thm.arsnova.controller.UserController.java

@RequestMapping(value = { "/{username}/resetpassword" }, method = RequestMethod.POST)
public void resetPassword(@PathVariable final String username, @RequestParam(required = false) final String key,
        @RequestParam(required = false) final String password, final HttpServletRequest request,
        final HttpServletResponse response) {
    DbUser dbUser = userService.getDbUser(username);
    if (null == dbUser) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);

        return;/*from   www.  j a v a 2  s .com*/
    }

    if (null != key) {
        if (!userService.resetPassword(dbUser, key, password)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    } else {
        userService.initiatePasswordReset(username);
    }
}

From source file:org.wiredwidgets.cow.server.web.ProcessDefinitionsController.java

/**
 * DELETE method for URL /processDefinitions?key={key}
 * Deletes all deployments for the specified key.  No executions of this process can be running.
 * @param key the process definition key
 *//*  w  ww.  ja v a  2 s. c om*/
@RequestMapping(method = RequestMethod.DELETE, params = { "key", "!versions" })
public void deleteProcessDef(@RequestParam("key") String key, HttpServletResponse response) {
    if (processDefsService.deleteProcessDefinitionsByKey(key)) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404
    }
}

From source file:com.github.jknack.handlebars.server.HbsServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    Writer writer = null;//from w w w  .j av a 2s.co m

    try {
        Template template = handlebars.compile(removeExtension(requestURI(request)));

        Object model = model(request);

        String output = template.apply(model);
        response.setCharacterEncoding(args.encoding);
        response.setContentType(args.contentType);
        writer = response.getWriter();
        writer.write(output);
    } catch (HandlebarsException ex) {
        handlebarsError(ex, response);
    } catch (JsonParseException ex) {
        logger.error("Unexpected error", ex);
        jsonError(ex, request, response);
    } catch (FileNotFoundException ex) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ex) {
        logger.error("Unexpected error", ex);
        throw ex;
    } catch (RuntimeException ex) {
        logger.error("Unexpected error", ex);
        throw ex;
    } catch (Exception ex) {
        logger.error("Unexpected error", ex);
        throw new ServletException(ex);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.mypackage.spring.controllers.ContactsSpringController.java

@RequestMapping(value = "/contacts/{id}", method = RequestMethod.GET)
public ModelAndView getAContact(@PathVariable String id) {
    ModelAndView modelAndView = new ModelAndView();
    try {//w w w.j  a  va 2s .co  m
        Contact contact = contactsController.getContact(id);

        modelAndView.addObject("contact", contact);
        List<Email> emailsList = contactsController.retrieveAllEmails(id);
        modelAndView.addObject("emailList", emailsList);
        modelAndView.addObject("contactId", id);
        modelAndView.setViewName("/viewContact.jsp");

    } catch (DalException ex) {
        logger.error("A database error occured.", ex);
        modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        modelAndView.addObject("errorMessage", "There was a an internal database error.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedIdentifierException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST);
        modelAndView.addObject("errorMessage", "An error occured because of a malformed id (caused by id = "
                + id + "). Please use only numeric values.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (ResourceNotFoundException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_NOT_FOUND);
        modelAndView.addObject("errorMessage", "Requested contact (with id = " + id + ") does not exist.");
        modelAndView.setViewName("/errorPage.jsp");
    }
    return modelAndView;
}

From source file:org.openmhealth.reference.filter.ExceptionFilter.java

/**
 * <p>/*from   w  ww.j  a va  2s.  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: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  w  w .  j ava2  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.");
    }
}