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:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPQuery.java

/**
 * Handles Get requests/*from ww w  . ja v  a  2 s  . c  o m*/
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int localPageSize = this.pageSize;

    ServletOutputStream out = response.getOutputStream();
    out = response.getOutputStream();

    Object[] resultSet = null;
    int pageNumber = 1;

    LexEVSHTTPUtils httpUtils = new LexEVSHTTPUtils(context);

    String queryType = httpUtils.getQueryType(request.getRequestURL().toString());

    String query = null;

    try {
        if (URLDecoder.decode(request.getQueryString(), "ISO-8859-1") != null) {
            query = URLDecoder.decode(request.getQueryString(), "ISO-8859-1");
        } else {
            throw new Exception("Query not defined" + getQuerySyntax());
        }
        if (query.indexOf("&username") > 0)
            query = query.substring(0, query.indexOf("&username"));

        validateQuery(query);
        httpUtils.setQueryArguments(query);

        httpUtils.setServletName(request.getRequestURL().toString());

        if (httpUtils.getPageSize() != null) {
            localPageSize = Integer.parseInt(httpUtils.getPageSize());
        } else {
            httpUtils.setPageSize(localPageSize);
        }

        resultSet = httpUtils.getResultSet();

        try {

            XMLOutputter xout = new XMLOutputter();
            org.jdom.Document domDoc = httpUtils.getXMLDocument(resultSet, pageNumber);

            if (queryType.endsWith("XML")) {
                response.setContentType("text/xml");
                xout.output(domDoc, out);
            } else if (queryType.endsWith("JSON")) {
                response.setContentType("application/x-javascript");
                if (httpUtils.getTargetPackageName() != null) {
                    printDocument(domDoc, jsonStyleSheet, out);

                }
            } else {
                response.setContentType("text/html");
                if (httpUtils.getTargetPackageName() != null) {
                    printDocument(domDoc, cacoreStyleSheet, out);
                }
            }

        } catch (Exception ex) {
            log.error("Print Results Exception: " + ex.getMessage());
            throw ex;
        }
    } catch (Exception ex) {

        log.error("Exception: ", ex);
        if (ex instanceof SelectionStrategyException
                || (ex.getCause() != null && ex.getCause() instanceof SelectionStrategyException)) {

            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "The requested Coding Scheme is not available. \n\n" + ex.getMessage());
        } else if (ex instanceof WebQueryException
                || (ex.getCause() != null && ex.getCause() instanceof WebQueryException)) {

            response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        }
    }
}

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

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST)
public @ResponseBody void likeVideo(@PathVariable("id") long id, Principal p, HttpServletResponse response)
        throws IOException {
    System.out.println("This is like again " + p.getName());
    Video v = null;/*from   ww w.j a v  a  2 s  .  c  o m*/
    if (!videos.exists(id)) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {
        v = videos.findOne(id);
        Set<String> likesUserNames = v.getLikesUsernames();
        // System.out.println("This is like again"+ p.getName());
        if (likesUserNames.contains(p.getName())) {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            //new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
        } else {

            // keep track of users have liked a video
            likesUserNames.add(p.getName());
            v.setLikesUsernames(likesUserNames);
            v.setLikes(likesUserNames.size());
            videos.save(v);
            response.setStatus(200);
        }
    }
}

From source file:com.google.gwt.dev.shell.GWTShellServlet.java

protected void processFileRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String pathInfo = request.getPathInfo();
    if (pathInfo.length() == 0 || pathInfo.equals("/")) {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><body><basefont face='arial'>");
        writer.println(//from  www .java 2s.c o  m
                "To launch an application, specify a URL of the form <code>/<i>module</i>/<i>file.html</i></code>");
        writer.println("</body></html>");
        return;
    }

    TreeLogger logger = getLogger();

    // Parse the request assuming it is module/resource.
    //
    RequestParts parts;
    try {
        parts = new RequestParts(request);
    } catch (UnableToCompleteException e) {
        sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND,
                "Don't know what to do with this URL: '" + pathInfo + "'");
        return;
    }

    String partialPath = parts.partialPath;
    String moduleName = parts.moduleName;

    // If the module is renamed, substitute the renamed module name
    ModuleDef moduleDef = loadedModulesByName.get(moduleName);
    if (moduleDef != null) {
        moduleName = moduleDef.getName();
    }

    if (partialPath == null) {
        // Redir back to the same URL but ending with a slash.
        //
        response.sendRedirect(moduleName + "/");
        return;
    } else if (partialPath.length() > 0) {
        // Both the module name and a resource.
        //
        doGetPublicFile(request, response, logger, partialPath, moduleName);
        return;
    } else {
        // Was just the module name, ending with a slash.
        //
        doGetModule(request, response, logger, parts);
        return;
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTUser.java

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//from w w  w . j a v  a  2  s  . c  om
        WSUserSearchCriteria c = restUtils.getWSUserSearchCriteria(getUserSearchInformation(req.getPathInfo()));

        WSUser userToDelete = new WSUser();
        userToDelete.setUsername(c.getName());
        userToDelete.setTenantId(c.getTenantId());

        if (isLoggedInUser(restUtils.getCurrentlyLoggedUser(), userToDelete)) {
            throw new ServiceException(HttpServletResponse.SC_FORBIDDEN,
                    "user: " + userToDelete.getUsername() + " can not to delete himself");
        } else if (validateUserForGetOrDelete(userToDelete)) {
            if (isAlreadyAUser(userToDelete)) {
                userAndRoleManagementService.deleteUser(userToDelete);
            } else {
                throw new ServiceException(HttpServletResponse.SC_NOT_FOUND,
                        "user: " + userToDelete.getUsername() + " was not found");
            }
        } else {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters");
        }
        if (log.isDebugEnabled()) {
            log.debug(userToDelete.getUsername() + " was deleted");
        }

        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }
}

From source file:nl.dtls.fairdatapoint.api.controller.MetadataControllerTest.java

/**
 * Check non existing dataset.//from  w  w  w.j ava 2 s .  co m
 * 
 * @throws Exception 
 */
@Test
public void nonExistingDataset() throws Exception {

    MockHttpServletRequest request;
    MockHttpServletResponse response;
    Object handler;

    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    request.setMethod("GET");
    request.addHeader(HttpHeaders.ACCEPT, "text/turtle");
    request.setRequestURI("/textmining/dumpy");
    handler = handlerMapping.getHandler(request).getHandler();
    handlerAdapter.handle(request, response, handler);
    assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
}

From source file:net.duckling.ddl.web.sync.FileContentController.java

@RequirePermission(target = "team", operation = "view")
@ResponseBody/*from   w w w .  j a v  a 2s .  co  m*/
@RequestMapping(params = "func=download")
public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam("fid") Long rid,
        @RequestParam(value = "fver", required = false) Long fver) {
    Context ctx = ContextUtil.retrieveContext(request);
    int tid = ctx.getTid();

    Resource resource = resourceService.getResource(rid.intValue(), tid);
    if (resource == null || LynxConstants.STATUS_DELETE.equals(resource.getStatus())) {
        Result<Object> result = new Result<Object>(Result.CODE_FILE_NOT_FOUND, Result.MESSAGE_FILE_NOT_FOUND);
        response.setHeader(DDL_API_RESULT_HEADER, result.toString());
        return;
    }

    if (resource.getItemType().equals(LynxConstants.TYPE_PAGE)) {
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(DDOC_FILE_CONTENT);
            if (rid == 254974) {
                throw new IOException("a test");
            }
            return;
        } catch (IOException e) {
            LOG.error(String.format("Fail to download rid: %d", rid), e);
            return;
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    FileVersion file = null;
    file = fver == null ? fileVersionService.getLatestFileVersion(rid.intValue(), tid)
            : fileVersionService.getFileVersion(rid.intValue(), tid, fver.intValue());
    if (file == null || LynxConstants.STATUS_DELETE.equals(file.getStatus())) {
        Result<Object> result = new Result<Object>(Result.CODE_FILE_NOT_FOUND, Result.MESSAGE_FILE_NOT_FOUND);
        response.setHeader(DDL_API_RESULT_HEADER, result.toString());
        LOG.error(String.format("Resource of rid:%d exists, but there is no valid file version.", rid));
        return;
    }

    if (NginxAgent.isNginxMode()) {
        String url = resourceOperateService.getDirectURL(file.getClbId(), String.valueOf(file.getClbVersion()),
                false);
        NginxAgent.setRedirectUrl(request, response, file.getTitle(), file.getSize(), url);
    } else {
        try {
            AttSaver fs = new AttSaver(response, request, file.getTitle());
            resourceOperateService.getContent(file.getClbId(), String.valueOf(file.getClbVersion()), fs);
        } catch (ResourceNotFound resourceNotFound) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            } catch (IOException ignored) {
            }
            LOG.error(String.format("Fail to get file %d from CLB.", file.getRid()), resourceNotFound);
        } catch (Exception e) {
            JsonResponse.error(response);
            LOG.error(String.format("Fail to get file %d from CLB.", file.getRid()), e);
        }
    }
}

From source file:com.paladin.mvc.RequestContext.java

public void not_found() throws IOException {
    error(HttpServletResponse.SC_NOT_FOUND);
}

From source file:ch.entwine.weblounge.test.harness.rest.PagesEndpointTest.java

/**
 * Tests the creation of a page./*w  w  w  .  j a v  a 2 s .c o m*/
 * 
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if page creation fails
 */
private void testCreate(String serverUrl) throws Exception {
    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages");
    HttpPost createPageRequest = new HttpPost(requestUrl);
    String[][] params = new String[][] { { "path", pagePath } };
    logger.debug("Creating new page at {}", createPageRequest.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, createPageRequest, params);
        assertEquals(HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
        assertEquals(0, response.getEntity().getContentLength());

        // Extract the id of the new page
        assertNotNull(response.getHeaders("Location"));
        String locationHeader = response.getHeaders("Location")[0].getValue();
        assertTrue(locationHeader.startsWith(serverUrl));
        pageId = locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
        assertEquals("Identifier doesn't have correct length", 36, pageId.length());
        logger.debug("Id of the new page is {}", pageId);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Make sure the page is not yet publicly reachable
    String requestByIdUrl = UrlUtils.concat(serverUrl, "/weblounge-pages/", pageId);
    HttpGet getPageRequest = new HttpGet(requestByIdUrl);
    httpClient = new DefaultHttpClient();
    logger.info("Requesting published page at {}", requestByIdUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, getPageRequest, null);
        assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:org.ngrinder.script.controller.DavSvnController.java

/**
 * Request Handler.//from w w w.j ava  2  s  .c o  m
 * 
 * @param request
 *            request
 * @param response
 *            response
 * @throws ServletException
 *             occurs when servlet has a problem.
 * @throws IOException
 *             occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        final String head = DAVPathUtil.head(request.getPathInfo());
        final User currentUser = userContext.getCurrentUser();
        // check the security. If the other user tries to the other user's
        // repo, deny it.
        if (!StringUtils.equals(currentUser.getUserId(), head)) {
            SecurityContextHolder.getContext().setAuthentication(null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    head + " is not accessible by " + currentUser.getUserId());
            return;
        }
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerExFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}

From source file:com.liferay.sync.servlet.DownloadServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {/* w  w  w.  j a  va  2  s .c o  m*/
        HttpSession session = request.getSession();

        if (PortalSessionThreadLocal.getHttpSession() == null) {
            PortalSessionThreadLocal.setHttpSession(session);
        }

        User user = PortalUtil.getUser(request);

        PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

        PermissionThreadLocal.setPermissionChecker(permissionChecker);

        String path = HttpUtil.fixPath(request.getPathInfo());
        String[] pathArray = StringUtil.split(path, CharPool.SLASH);

        if (pathArray[0].equals("image")) {
            long imageId = GetterUtil.getLong(pathArray[1]);

            sendImage(response, imageId);
        } else if (pathArray[0].equals("zip")) {
            String zipFileIds = ParamUtil.get(request, "zipFileIds", StringPool.BLANK);

            if (Validator.isNull(zipFileIds)) {
                throw new IllegalArgumentException("Missing parameter zipFileIds");
            }

            JSONArray zipFileIdsJSONArray = JSONFactoryUtil.createJSONArray(zipFileIds);

            sendZipFile(response, user.getUserId(), zipFileIdsJSONArray);
        } else if (pathArray[0].equals("zipfolder")) {
            long repositoryId = ParamUtil.getLong(request, "repositoryId");
            long folderId = ParamUtil.getLong(request, "folderId");

            if (repositoryId == 0) {
                throw new IllegalArgumentException("Missing parameter repositoryId");
            } else if (folderId == 0) {
                throw new IllegalArgumentException("Missing parameter folderId");
            }

            sendZipFolder(response, user.getUserId(), repositoryId, folderId);
        } else {
            long groupId = GetterUtil.getLong(pathArray[0]);
            String uuid = pathArray[1];

            Group group = GroupLocalServiceUtil.fetchGroup(groupId);

            if ((group == null) || !SyncUtil.isSyncEnabled(group)) {
                response.setHeader(_ERROR_HEADER, SyncSiteUnavailableException.class.getName());

                ServletResponseUtil.write(response, new byte[0]);

                return;
            }

            boolean patch = ParamUtil.getBoolean(request, "patch");

            if (patch) {
                sendPatch(request, response, user.getUserId(), groupId, uuid);
            } else {
                sendFile(request, response, user.getUserId(), groupId, uuid);
            }
        }
    } catch (NoSuchFileEntryException nsfee) {
        PortalUtil.sendError(HttpServletResponse.SC_NOT_FOUND, nsfee, request, response);
    } catch (NoSuchFileVersionException nsfve) {
        PortalUtil.sendError(HttpServletResponse.SC_NOT_FOUND, nsfve, request, response);
    } catch (Exception e) {
        PortalUtil.sendError(e, request, response);
    }
}