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:com.googlesource.gerrit.plugins.github.velocity.VelocityStaticServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException {
    final Resource p = local(req);
    if (p == null) {
        CacheHeaders.setNotCacheable(rsp);
        rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;//w w  w . j  av a2 s. c  o m
    }

    final String type = contentType(p.getName());
    final byte[] tosend;
    if (!type.equals("application/x-javascript") && RPCServletUtils.acceptsGzipEncoding(req)) {
        rsp.setHeader("Content-Encoding", "gzip");
        tosend = compress(readResource(p));
    } else {
        tosend = readResource(p);
    }

    CacheHeaders.setCacheable(req, rsp, 12, TimeUnit.HOURS);
    rsp.setDateHeader("Last-Modified", p.getLastModified());
    rsp.setContentType(type);
    rsp.setContentLength(tosend.length);
    final OutputStream out = rsp.getOutputStream();
    try {
        out.write(tosend);
    } finally {
        out.close();
    }
}

From source file:org.jboss.as.test.clustering.cluster.singleton.SingletonDeploymentTestCase.java

@Test
public void test(@ArquillianResource @OperateOnDeployment(DEPLOYMENT_1) ManagementClient client1,
        @ArquillianResource @OperateOnDeployment(DEPLOYMENT_2) ManagementClient client2,
        @ArquillianResource(TraceServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(TraceServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws Exception {

    // In order to test undeploy in case another node becomes elected as the master, we need an election policy that will ever trigger that code path (WFLY-8184)
    executeOnNodesAndReload(/*  w  ww. j a  v  a  2  s.c om*/
            "/subsystem=singleton/singleton-policy=default/election-policy=simple:write-attribute(name=name-preferences,value="
                    + Arrays.toString(NODES) + ")",
            client1, client2);

    this.deploy(SINGLETON_DEPLOYMENT_1);
    Thread.sleep(DELAY);
    this.deploy(SINGLETON_DEPLOYMENT_2);
    Thread.sleep(DELAY);

    URI uri1 = TraceServlet.createURI(new URL(baseURL1.getProtocol(), baseURL1.getHost(), baseURL1.getPort(),
            "/" + this.deploymentName + "/"));
    URI uri2 = TraceServlet.createURI(new URL(baseURL2.getProtocol(), baseURL2.getHost(), baseURL2.getPort(),
            "/" + this.deploymentName + "/"));

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        this.undeploy(SINGLETON_DEPLOYMENT_1);

        Thread.sleep(DELAY);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        this.deploy(SINGLETON_DEPLOYMENT_1);

        Thread.sleep(DELAY);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        this.undeploy(SINGLETON_DEPLOYMENT_2);

        Thread.sleep(DELAY);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        this.deploy(SINGLETON_DEPLOYMENT_2);

        Thread.sleep(DELAY);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        this.undeploy(SINGLETON_DEPLOYMENT_1, SINGLETON_DEPLOYMENT_2);

        executeOnNodesAndReload(
                "/subsystem=singleton/singleton-policy=default/election-policy=simple:undefine-attribute(name=name-preferences)",
                client1, client2);
    }
}

From source file:org.lbogdanov.poker.web.page.SessionPage.java

/**
 * Creates a new instance of <code>Session</code> page.
 *//*  w w w  .  jav a  2 s. c  o  m*/
public SessionPage(PageParameters parameters) {
    session = sessionService.find(parameters.get("code").toString());
    if (session == null) {
        throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND, "Session not found");
    }

    final TextArea<String> chatMsg = new TextArea<String>("chatMsg", Model.of(""));
    Form<?> chatForm = new Form<Void>("chatForm");
    chatForm.add(chatMsg, new AjaxFallbackButton("chatSend", chatForm) {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            ChatMessage message = new ChatMessage(getSession().getId(), userService.getCurrentUser(),
                    chatMsg.getModelObject());
            post(session.getCode(), message);
        }

        @Override
        protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
            super.updateAjaxAttributes(attributes);
            AjaxCallListener listener = new AjaxCallListener();
            listener.onPrecondition("return $('#chatMsg').val().length > 0;")
                    .onBeforeSend("Poker.toggleForm('chatForm', true);")
                    .onComplete("Poker.msgSent(jqXHR); Poker.toggleForm('chatForm', false);");
            attributes.getAjaxCallListeners().add(listener);
        }

    });

    LimitableLabel name = new LimitableLabel("session.name", session.getName());
    if (!Strings.isNullOrEmpty(session.getDescription())) {
        name.add(AttributeModifier.append("class", "tip"),
                AttributeModifier.append("title", session.getDescription()));
    }

    add(chatForm.setOutputMarkupId(true), name.setMaxLength(LABEL_MAX_LENGTH),
            new BodylessLabel("session.code", session.getCode()).setMaxLength(LABEL_MAX_LENGTH),
            new BodylessLabel("session.author", session.getAuthor()).setMaxLength(LABEL_MAX_LENGTH),
            new BodylessLabel("session.created", formatDate(session.getCreated()))
                    .setMaxLength(LABEL_MAX_LENGTH));
}

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

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike", method = RequestMethod.POST)
public @ResponseBody void unlikeVideo(@PathVariable("id") long id, HttpServletRequest request,
        HttpServletResponse response) {/* w  w w. j  a v a 2 s  . c om*/
    Video video = videos.findOne(id);
    if (video != null) {
        Set<String> users = video.getLikesUserNames();
        String user = request.getRemoteUser();
        if (users.contains(user)) {
            users.remove(user);
            video.setLikesUserNames(users);
            video.setLikes(users.size());
            videos.save(video);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.flexive.war.servlet.DownloadServlet.java

@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String uri = FxServletUtils.stripSessionId(URLDecoder.decode(
            request.getRequestURI().substring(request.getContextPath().length() + BASEURL.length()), "UTF-8"));
    final FxPK pk;
    String xpath = null;//from  w  ww .  j  a va 2s. c  o m
    if (uri.startsWith("tree")) {
        // get PK via tree path
        final String[] parts = StringUtils.split(uri, "/", 3);
        if (parts.length != 3 || !"tree".equals(parts[0])) {
            FxServletUtils.sendErrorMessage(response, "Invalid download request: " + uri);
            return;
        }

        // get tree node by FQN path
        final FxTreeMode treeMode = "edit".equals(parts[1]) ? FxTreeMode.Edit : FxTreeMode.Live;
        final long nodeId;
        try {
            nodeId = EJBLookup.getTreeEngine().getIdByFQNPath(treeMode, FxTreeNode.ROOT_NODE, "/" + parts[2]);
        } catch (FxApplicationException e) {
            FxServletUtils.sendErrorMessage(response, "Failed to resolve file path: " + e.getMessage());
            return;
        }
        if (nodeId == -1) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // use content associated with tree node
        try {
            pk = EJBLookup.getTreeEngine().getNode(treeMode, nodeId).getReference();
        } catch (FxApplicationException e) {
            FxServletUtils.sendErrorMessage(response,
                    "Failed to load tree node " + nodeId + ": " + e.getMessage());
            return;
        }
    } else {
        // get PK
        if (!uri.startsWith("pk")) {
            FxServletUtils.sendErrorMessage(response, "Invalid download request: " + uri);
            return;
        }
        try {
            pk = FxPK.fromString(uri.substring(2, uri.indexOf('/')));
        } catch (IllegalArgumentException e) {
            FxServletUtils.sendErrorMessage(response, "Invalid primary key in download request: " + uri);
            return;
        }

        // extract xpath
        try {
            xpath = FxSharedUtils.decodeXPath(uri.substring(uri.indexOf('/') + 1, uri.lastIndexOf('/')));
        } catch (IndexOutOfBoundsException e) {
            // no XPath provided, use default binary XPath
        }
    }

    // load content
    final FxContent content;
    try {
        content = EJBLookup.getContentEngine().load(pk);
    } catch (FxApplicationException e) {
        FxServletUtils.sendErrorMessage(response, "Failed to load content: " + e.getMessage());
        return;
    }

    if (xpath == null) {
        // get default binary XPath from type
        final FxType type = CacheAdmin.getEnvironment().getType(content.getTypeId());
        if (type.getMainBinaryAssignment() != null) {
            xpath = type.getMainBinaryAssignment().getXPath();
        } else {
            FxServletUtils.sendErrorMessage(response, "Invalid xpath/filename in download request: " + uri);
            return;
        }
    }

    final String binaryIdParam = request.getParameter("hintBinaryId");
    final long hintBinaryId = StringUtils.isNumeric(binaryIdParam) ? Long.parseLong(binaryIdParam) : -1;

    // get binary descriptor
    final BinaryDescriptor descriptor;

    if (hintBinaryId != -1) {
        final BinaryDescriptor foundDescriptor = findBinaryDescriptor(content, hintBinaryId);

        if (foundDescriptor == null) {
            FxServletUtils.sendErrorMessage(response,
                    "Expected binary ID not present in content" + pk + ": " + hintBinaryId);
            return;
        }

        descriptor = foundDescriptor;
    } else {
        try {
            descriptor = (BinaryDescriptor) content.getValue(xpath).getBestTranslation();
        } catch (Exception e) {
            FxServletUtils.sendErrorMessage(response, "Failed to load binary value: " + e.getMessage());
            return;
        }
    }
    // stream content
    try {
        response.setContentType(descriptor.getMimeType());
        response.setContentLength((int) descriptor.getSize());
        if (request.getParameter("inline") == null || "false".equals(request.getParameter("inline"))) {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + descriptor.getName() + "\";");
        }
        descriptor.download(response.getOutputStream());
    } catch (Exception e) {
        FxServletUtils.sendErrorMessage(response, "Download failed: " + e.getMessage());
        //noinspection UnnecessaryReturnStatement
        return;
    } finally {
        response.getOutputStream().close();
    }
}

From source file:javax.faces.webapp.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 .j  a  va  2s. 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) {
        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:com.sap.dirigible.runtime.registry.RegistryServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    String repositoryPath = null;
    final String requestPath = request.getPathInfo();
    boolean deep = false;
    if (requestPath == null) {
        deep = true;/*from   w  w w . j  a va2  s .  co m*/
    }
    final OutputStream out = response.getOutputStream();
    try {
        repositoryPath = extractRepositoryPath(request);
        final IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity != null) {
            if (entity instanceof IResource) {
                data = buildResourceData(entity, request, response);
            } else if (entity instanceof ICollection) {
                String collectionPath = request.getRequestURI().toString();
                String acceptHeader = request.getHeader(ACCEPT_HEADER);
                if (acceptHeader != null && acceptHeader.contains(JSON)) {
                    if (!collectionPath.endsWith(IRepository.SEPARATOR)) {
                        collectionPath += IRepository.SEPARATOR;
                    }
                    data = buildCollectionData(deep, entity, collectionPath);
                } else {
                    // welcome file support
                    IResource index = ((ICollection) entity).getResource(INDEX_HTML);
                    if (index.exists() && (collectionPath.endsWith(IRepository.SEPARATOR))) {
                        data = buildResourceData(index, request, response);
                    } else {
                        // listing of collections is forbidden
                        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                                LISTING_OF_FOLDERS_IS_FORBIDDEN);
                        return;
                    }
                }
            } else {
                exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                        LISTING_OF_FOLDERS_IS_FORBIDDEN);
                return;
            }
        } else {
            exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NOT_FOUND,
                    String.format("Resource at [%s] does not exist", requestPath));
            return;
        }

        if (entity instanceof IResource) {
            final IResource resource = (IResource) entity;
            String mimeType = null;
            String extension = ContentTypeHelper.getExtension(resource.getName());
            if ((mimeType = ContentTypeHelper.getContentType(extension)) != null) {
                response.setContentType(mimeType);
            } else {
                response.setContentType(resource.getContentType());
            }
        }
        sendData(out, data);
    } catch (final IllegalArgumentException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (final MissingResourceException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } catch (final RuntimeException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }
}

From source file:eu.dasish.annotation.backend.rest.TargetResource.java

/**
 * /* ww w.ja  va  2s  .c  om*/
 * @param externalIdentifier the external UUID of a target.
 * @return a {@link ReferenceList} element representing the list of h-references of the targets that 
 * refer to the same link as the target with "externalIdentifier".
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{targetid: " + BackendConstants.regExpIdentifier + "}/versions")
@Transactional(readOnly = true)
public JAXBElement<ReferenceList> getSiblingTargets(@PathParam("targetid") String externalIdentifier)
        throws IOException {
    Map params = new HashMap();
    try {
        ReferenceList result = (ReferenceList) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetSiblingTargets(), Resource.TARGET, Access.READ, externalIdentifier);
        if (result != null) {
            return new ObjectFactory().createReferenceList(result);
        } else {
            return new ObjectFactory().createReferenceList(new ReferenceList());
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return new ObjectFactory().createReferenceList(new ReferenceList());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return new ObjectFactory().createReferenceList(new ReferenceList());
    }
}

From source file:alfio.controller.api.admin.AdminWaitingQueueApiController.java

@RequestMapping(value = "/load", method = RequestMethod.GET)
public List<WaitingQueueSubscription> loadAllSubscriptions(@PathVariable("eventName") String eventName,
        Principal principal, HttpServletResponse response) {
    Optional<List<WaitingQueueSubscription>> count = optionally(
            () -> eventManager.getSingleEvent(eventName, principal.getName()))
                    .map(e -> waitingQueueManager.loadAllSubscriptionsForEvent(e.getId()));
    if (count.isPresent()) {
        return count.get();
    }/*  w  w  w  .ja va2  s. c  om*/
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    return Collections.emptyList();
}