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:info.magnolia.cms.servlets.ResourceDispatcher.java

/**
 * Get the requested resource and copy it to the ServletOutputStream, bit by bit.
 *
 * @param req HttpServletRequest as given by the servlet container
 * @param res HttpServletResponse as given by the servlet container
 * @throws IOException standard servlet exception
 *//*w w w .  jav  a  2s  .  co  m*/
private void handleResourceRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String resourceHandle = (String) req.getAttribute(Aggregator.HANDLE);
    if (log.isDebugEnabled()) {
        log.debug("handleResourceRequest, resourceHandle=\"" + resourceHandle + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (StringUtils.isNotEmpty(resourceHandle)) {
        HierarchyManager hm = (HierarchyManager) req.getAttribute(Aggregator.HIERARCHY_MANAGER);
        InputStream is = null;
        try {
            is = getNodedataAstream(resourceHandle, hm, res);
            if (null != is) {
                // todo find better way to discover if resource could be compressed, implement as in "cache"
                // browsers will always send header saying either it can decompress or not, but
                // resources like jpeg which is already compressed should be not be written on
                // zipped stream otherwise some browsers takes a long time to render
                sendUnCompressed(is, res);
                IOUtils.closeQuietly(is);
                return;
            }
        } catch (IOException e) {
            // don't log at error level since tomcat tipically throws a
            // org.apache.catalina.connector.ClientAbortException if the user stops loading the page
            if (log.isDebugEnabled())
                log.debug("Exception while dispatching resource  " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$
                        + e.getMessage(), e);
        } catch (Exception e) {
            log.error("Exception while dispatching resource  " + e.getClass().getName() + ": " + e.getMessage(), //$NON-NLS-1$//$NON-NLS-2$
                    e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Resource not found, redirecting request for [" + req.getRequestURI() + "] to 404 URI"); //$NON-NLS-1$
    }

    if (!res.isCommitted()) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
        log.info("Unable to redirect to 404 page, response is already committed"); //$NON-NLS-1$
    }

}

From source file:com.tasktop.c2c.server.scm.web.GitHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final boolean containerSupportsChunkedIO = computeContainerSupportsChunkedIO();

    String pathInfo = request.getPathInfo();
    log.info("Git request: " + request.getMethod() + " " + request.getRequestURI() + " " + pathInfo);

    Repository repository = null;//from w ww. j  a  v  a2 s .co  m
    try {
        // only work on Git requests
        Matcher matcher = pathInfo == null ? null : GIT_COMMAND_PATTERN.matcher(pathInfo);
        if (matcher == null || !matcher.matches()) {
            log.info("Unexpected path: " + pathInfo);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String requestCommand = matcher.group(1);
        String requestPath = matcher.group(2);

        // sanity check on path, disallow path separator components
        if (requestPath == null || requestPath.contains("/") || requestPath.contains("..")) {
            badPathResponse();
        }

        repository = repositoryResolver.open(request, requestPath);

        InputStream requestInput = request.getInputStream();
        if (!containerSupportsChunkedIO) {
            requestInput = new ChunkedInputStream(requestInput);
        }

        MultiplexingOutputStream mox = createMultiplexingOutputStream(response, containerSupportsChunkedIO);
        // indicate that we're ok to handle the request
        // note that following this there will be a two-way communication with the process
        // that might still encounter errors. That's ok.
        startOkResponse(response, containerSupportsChunkedIO);

        // identify the git command
        GitCommand command = GitCommand.fromCommandName(requestCommand);
        if (command != null) {
            // permissions check
            if (!Security.hasOneOfRoles(command.getRoles())) {
                log.info("Access denied to " + Security.getCurrentUser() + " for " + command.getCommandName()
                        + " on " + TenancyUtil.getCurrentTenantProjectIdentifer() + " " + requestPath);
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            switch (command) {
            case RECEIVE_PACK:
                ReceivePack rp = new ReceivePack(repository);
                rp.setPostReceiveHook(postReceiveHook);
                rp.receive(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            case UPLOAD_PACK:
                UploadPack up = new UploadPack(repository);
                up.upload(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        // at this stage we're done with IO
        // send the exit value and closing chunk
        try {
            int exitValue = 0;

            if (exitValue != 0) {
                log.info("Exit value: " + exitValue);
            }
            mox.writeExitCode(exitValue);
            mox.close();
        } catch (IOException e) {
            // ignore
            log.debug("Cannot complete writing exit state", e);
        }

        // clear interrupt status
        Thread.interrupted();

    } catch (ErrorResponseException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotAuthorizedException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotEnabledException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } finally {
        log.info("Git request complete");
        if (repository != null) {
            repository.close();
        }
    }
}

From source file:jp.terasoluna.fw.web.struts.actions.ClearSessionAction.java

/**
 * ZbVNA?s?AtH??[h?B/*from  ww  w. j a  va  2 s  .c  om*/
 * <p>
 *  ???L?[P???A
 *  J??p?A???I?B
 * </p>
 * @param mapping ANV}bsO
 * @param form ANVtH?[
 * @param request <code>HTTP</code>NGXg
 * @param response <code>HTTP</code>X|X
 * @return J??
 */
@Override
public ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    HttpSession session = request.getSession();

    if (clearSessionKeys != null) {
        for (int cnt = 0; cnt < clearSessionKeys.size(); cnt++) {
            String sKey = (String) clearSessionKeys.get(cnt);
            if (log.isDebugEnabled()) {
                log.debug("removing [" + sKey + "] from HttpSession");
            }
            //ZbV???s
            session.removeAttribute(sKey);
        }
    }

    // p??[^??itH??[h??j
    String path = mapping.getParameter();

    if (path == null) {
        // p??[^?????A(404)G?[p
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e) {
            log.error("Error page(404) forwarding failed.");

            throw new SystemException(e, FORWARD_ERRORPAGE_ERROR);
        }
        return null;
    }

    // ANVtH??[h??
    ActionForward retVal = new ActionForward(path);

    return retVal;

}

From source file:com.bt.aloha.batchtest.ultramonkey.Servlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug(request.getPathInfo() + ":" + request.getQueryString());
    Properties resultProperties = new Properties();
    resultProperties.put("local.host.name", request.getLocalName());
    resultProperties.put("local.host.port", Integer.toString(request.getLocalPort()));
    resultProperties.put("remote.host.name", request.getRemoteHost());
    resultProperties.put("remote.host.port", Integer.toString(request.getRemotePort()));
    resultProperties.put("makeCall.count", Integer.toString(makeCallCount));
    resultProperties.put("terminateCall.count", Integer.toString(terminateCallCount));
    resultProperties.put("incomingCall.count", Integer.toString(((ServiceImpl) service).getIncomingCount()));
    String result = "something or rather";
    String resultKey = "callid";
    if (request.getPathInfo().equalsIgnoreCase("/makecall")) {
        makeCallCount++;/*  w w w.jav  a  2s  .c  o m*/
        String caller = request.getParameter("caller");
        String callee = request.getParameter("callee");
        result = this.service.makeCall(caller, callee);
    } else if (request.getPathInfo().equalsIgnoreCase("/terminatecall")) {
        terminateCallCount++;
        String callid = request.getParameter("callid");
        service.terminateCall(callid);
        result = callid;
    } else if (request.getPathInfo().equalsIgnoreCase("/reset")) {
        makeCallCount = 0;
        terminateCallCount = 0;
        ((ServiceImpl) service).setIncomingCount(0);
    } else if (request.getPathInfo().equalsIgnoreCase("/status")) {
        result = "Sample SpringRing web application";
        resultKey = "status";
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    resultProperties.put(resultKey, result);
    resultProperties.store(response.getOutputStream(), "Response generated on:");
}

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

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)/* w  w  w .  ja v a 2 s .c om*/
public void unlikeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal p) {
    Video v = videos.findOne(id);
    if (v == null) {
        sendError(response, HttpServletResponse.SC_NOT_FOUND, "Video not found");
        return;
    }
    v.unlikeVideo(p.getName());
    videos.save(v);
}

From source file:com.jaspersoft.jasperserver.rest.RESTServlet.java

/**
 * The REST servlet check for the resource type that has been requested.<br>
 * The resource is represented by the url i.e. /rest/<b>resource</b> or /rest/<b>report</b>
 * The resource logic is implemented by extending a RESTService.<br>
 * The RESTService handled for a specific request is configured in the file shared-config\applicationContext-rest-services.xml. It is a map which
 * binds urls to RESTServices. The RESTService implementation is in charge to accept or not the specific method type.
 *
 * @param req  HttpServletRequest/*from w  w w .  j av  a 2 s.com*/
 * @param resp  HttpServletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("-------------------------------------------------------------------------------- ");
    }

    // This print writer is used only in case of exception, but in general exception should be always
    // handled inside the RESTService implementation, if available.
    PrintWriter pw = null;
    String serviceName = null;
    String path = null;

    try {

        // Get the name of the service requested by the user
        path = req.getPathInfo();
        if (path == null) {
            // error...
            log.error("request params: Path: " + path);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid");
            return;
        }

        serviceName = utils.extractServiceName(path);

        // If the service name is null or empty, return an error.
        if (serviceName == null || serviceName.length() == 0) {
            log.error("request params: Service" + serviceName + " Path: " + path);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid");
            return;
        }

        RESTService service = registry.getService(serviceName);
        if (service == null) {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid");
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("request params: Path: " + path + " Requested Service: " + serviceName
                    + " Service from registry: " + service.getClass());
        }

        resp.setContentType("text/xml; charset=UTF-8");
        service.execute(req, resp);
    } catch (ServiceException ex) {
        if (log.isDebugEnabled())
            log.debug("Error executing a REST service: " + ex.getErrorCode(), ex);
        // The servlet is able to map common ServiceException errors with most appropriate REST (HTTP) error codes...
        // This should be really just the latest case, when a more specific error is not available.
        // In general the service implementation should take care to send to the client the proper response.
        switch (ex.getErrorCode()) {
        case ServiceException.RESOURCE_NOT_FOUND: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_NOT_FOUND + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "");
            break;
        }
        case ServiceException.RESOURCE_BAD_REQUEST: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ex.getMessage());
            break;
        }
        case ServiceException.FORBIDDEN: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, ex.getMessage());
            break;
        }
        default: {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
        }
        }
    }

    catch (UnsupportedOperationException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_NOT_IMPLEMENTED + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_NOT_IMPLEMENTED, resp, "");
    }

    catch (ReportJobNotFoundException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
    }

    catch (JSExceptionWrapper ex) {
        Exception e = ex.getOriginalException();
        if (e instanceof ConstraintViolationException || e instanceof DataIntegrityViolationException) {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, "");
        } else {
            log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                    + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
            utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
        }
    }

    catch (JSValidationException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
    }

    catch (AccessDeniedException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, ex.getMessage());

    }

    catch (IllegalStateException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");

    }

    catch (IllegalArgumentException ex) {
        log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: "
                + HttpServletResponse.SC_BAD_REQUEST + " Error: " + ex.getMessage(), ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");

    } catch (Exception ex) {
        // This should Never happen. If it does, it's probably an implementation bug, or the remote service
        // implementation did not provide a better or specific error.
        log.error("Error executing a REST service", ex);
        utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "");
    }
}

From source file:io.wcm.caravan.io.http.impl.CaravanHttpClientImplIntegrationTest.java

@Before
public void setUp() {
    ArchaiusConfig.initialize();//from ww  w. java  2 s . c  o m
    ArchaiusConfig.getConfiguration()
            .setProperty(SERVICE_NAME + CaravanHttpServiceConfig.THROW_EXCEPTION_FOR_STATUS_500, true);
    wireMockHost = "localhost:" + wireMock.port();

    context.registerInjectActivateService(new SimpleLoadBalancerFactory());
    serviceConfig = context.registerInjectActivateService(new CaravanHttpServiceConfig(),
            getServiceConfigProperties(wireMockHost, "auto"));
    context.registerInjectActivateService(new CaravanHttpThreadPoolConfig(),
            ImmutableMap.of(CaravanHttpThreadPoolConfig.THREAD_POOL_NAME_PROPERTY, "default"));

    context.registerInjectActivateService(new LoadBalancerCommandFactory());
    context.registerInjectActivateService(new HttpClientFactoryImpl());

    context.registerInjectActivateService(new CaravanHttpClientConfig(),
            Collections.singletonMap(CaravanHttpClientConfig.SERVLET_CLIENT_ENABLED, true));
    context.registerInjectActivateService(new ServletHttpClient());
    context.registerInjectActivateService(new ApacheHttpClient());
    context.registerInjectActivateService(new RibbonHttpClient());

    client = context.registerInjectActivateService(new CaravanHttpClientImpl());

    // setup wiremock
    wireMock.stubFor(get(urlEqualTo(HTTP_200_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody(DUMMY_CONTENT)));
    wireMock.stubFor(
            get(urlEqualTo(HTTP_404_URI)).willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
    wireMock.stubFor(get(urlEqualTo(HTTP_500_URI))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
    wireMock.stubFor(get(urlEqualTo(CONNECT_TIMEOUT_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody(DUMMY_CONTENT)));
    wireMock.stubFor(get(urlEqualTo(RESPONSE_TIMEOUT_URI))
            .willReturn(aResponse().withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8)
                    .withBody(DUMMY_CONTENT).withFixedDelay(1000)));

    assertTrue(client.hasValidConfiguration(SERVICE_NAME));

}

From source file:br.com.siprot.framework.servlet.FacesServlet.java

public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String pathInfo = httpRequest.getPathInfo();

    // if it is a prefix mapping ...
    if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF"))) {
        StringBuffer buffer = new StringBuffer();

        buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
        buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
        buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
        buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
        buffer.append("\n request URI is ").append(httpRequest.getRequestURI());

        log.warn(buffer.toString());/*from   w ww  . jav a  2 s .c  o  m*/

        // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?

        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (log.isTraceEnabled())
        log.trace("service begin");
    FacesContext facesContext = _facesContextFactory.getFacesContext(_servletConfig.getServletContext(),
            request, response, _lifecycle);
    try {
        _lifecycle.execute(facesContext);
        _lifecycle.render(facesContext);
    } catch (Throwable e) {
        //bloco de tratamento para excecao tratada
        if (e instanceof FacesException) {
            try {
                ErrorHandler.handleException(facesContext, (Exception) e);
                _lifecycle.render(facesContext);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
        //fim do bloco de  tratamento
        else if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e.getMessage() != null) {
            throw new ServletException(e.getMessage(), e);
        } else {
            throw new ServletException(e);
        }
    } finally {
        facesContext.release();
    }
    if (log.isTraceEnabled())
        log.trace("service end");
}

From source file:org.dspace.webmvc.controller.ResourceController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path)) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    }//from   ww  w. j  ava  2s  .co m

    final URL url;
    try {
        url = req.getSession().getServletContext().getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }

    final String mimeType = getMimeType(req, path);

    final String realpath = req.getSession().getServletContext().getRealPath(path);
    if (url != null && realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile()) {
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        } else {
            return new StaticFile(f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url);
        }
    } else {
        ClassPathResource cpr = new ClassPathResource(path);
        if (cpr.exists()) {
            URL cprURL = null;
            try {
                cprURL = cpr.getURL();

                // Try as a JAR Entry
                final ZipEntry ze = ((JarURLConnection) cprURL.openConnection()).getJarEntry();
                if (ze != null) {
                    if (ze.isDirectory()) {
                        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                    } else {
                        return new StaticFile(ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req),
                                cprURL);
                    }
                } else {
                    // Unexpected?
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                }
            } catch (ClassCastException e) {
                // Unknown resource type
                if (url != null) {
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                } else {
                    return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
                }
            } catch (IOException e) {
                return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
            }
        } else {
            return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");
        }
    }
}

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

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

    Long l_id;//from   w  w w. j  a v a2 s  .co  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");
}