List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_FOUND
int SC_NOT_FOUND
To view the source code for javax.servlet.http HttpServletResponse SC_NOT_FOUND.
Click Source Link
From source file:org.clothocad.phagebook.controllers.ProductController.java
@RequestMapping(value = "/createProduct", method = RequestMethod.POST) protected void createProduct(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); Map createUserMap = new HashMap(); String username = "test" + System.currentTimeMillis(); createUserMap.put("username", username); createUserMap.put("password", "password"); clothoObject.createUser(createUserMap); clothoObject.logout();//from w ww.j a v a 2 s .c om Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", "password"); clothoObject.login(loginMap); // Object pProductUrl = params.get("productUrl"); String productUrl = pProductUrl != null ? (String) pProductUrl : ""; Object pCompanyId = params.get("company"); String companyId = pCompanyId != null ? (String) pCompanyId : ""; Object pGoodType = params.get("goodType"); String goodType = pGoodType != null ? (String) pGoodType : ""; Object pCost = params.get("cost"); Double cost = pCost != null ? Double.parseDouble((String) pCost) : -1.0d; Object pQuantity = params.get("quantity"); Integer quantity = pQuantity != null ? Integer.parseInt((String) pQuantity) : -1; Object pName = params.get("name"); String name = pName != null ? (String) pName : ""; Object pDescription = params.get("description"); String description = pDescription != null ? (String) pDescription : ""; Vendor comp = new Vendor(); boolean isValidRequest = false; if ((!name.isEmpty() && (cost > 0) && (quantity > 0) && !companyId.isEmpty())) { isValidRequest = true; comp = ClothoAdapter.getVendor(companyId, clothoObject); if (comp.getId().equals("")) { isValidRequest = false; response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentType("application/json"); PrintWriter out = response.getWriter(); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "No Company with that id exists"); out.print(responseJSON.toString()); out.flush(); out.close(); clothoObject.logout(); return; } } if (isValidRequest) { Product prod = new Product(); prod.setName(name); prod.setCost(cost); prod.setInventory(quantity); prod.setCompanyId(comp.getId()); prod.setDescription(description); prod.setProductURL(productUrl); prod.setGoodType(GoodType.valueOf((!goodType.equals("")) ? goodType : "INSTRUMENT")); //everything is set for that product ClothoAdapter.createProduct(prod, clothoObject); JSONObject product = new JSONObject(); product.put("id", prod.getId()); product.put("name", prod.getName()); response.setStatus(HttpServletResponse.SC_CREATED); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(product); out.flush(); out.close(); clothoObject.logout(); conn.closeConnection(); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:net.bhira.sample.api.controller.DepartmentController.java
/** * Fetch the instance of {@link net.bhira.sample.model.Department} represented by given * departmentId and return it as JSON object. * // w w w .ja v a2 s . c o m * @param departmentId * the ID for {@link net.bhira.sample.model.Department}. * @param response * the http response to which the results will be written. * @return an instance of {@link net.bhira.sample.model.Department} as JSON. */ @RequestMapping(value = "/department/{departmentId}", method = RequestMethod.GET) @ResponseBody public Callable<String> getDepartment(@PathVariable long departmentId, HttpServletResponse response) { return new Callable<String>() { public String call() throws Exception { String body = ""; try { LOG.debug("servicing GET department/{}", departmentId); Department department = departmentService.load(departmentId); LOG.debug("GET department/{}, found = {}", departmentId, department != null); if (department == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { body = JsonUtil.createGson().toJson(department); } } catch (Exception ex) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); body = ex.getLocalizedMessage(); LOG.warn("Error loading department/{}. {}", departmentId, body); LOG.debug("Load error stacktrace: ", ex); } return body; } }; }
From source file:com.haulmont.cuba.core.controllers.FileDownloadController.java
protected FileDescriptor getFileDescriptor(HttpServletRequest request, HttpServletResponse response) throws IOException { UUID fileId;/*from w ww . j a v a 2 s. co m*/ try { fileId = UUID.fromString(request.getParameter("f")); } catch (Exception e) { log.error("Error parsing fileId from URL param", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } FileDescriptor fileDescriptor = dataService.load(new LoadContext<>(FileDescriptor.class).setId(fileId)); if (fileDescriptor == null) response.sendError(HttpServletResponse.SC_NOT_FOUND); return fileDescriptor; }
From source file:nl.dtls.fairdatapoint.api.controller.MetadataControllerTest.java
/** * Check non existing catalog.//from ww w . j a v a 2 s . c o m * * @throws Exception */ @Test public void nonExistingCatalog() 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("/dumpy"); handler = handlerMapping.getHandler(request).getHandler(); handlerAdapter.handle(request, response, handler); assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); }
From source file:eu.trentorise.smartcampus.permissionprovider.auth.google.GoogleController.java
/** * This rest web service is the one that google called after login (callback * url). First it retrieve code and token that google sends back. It checks * if code and token are not null, then if token is the same that was saved * in session. If it is not response status is UNAUTHORIZED, otherwise it * retrieves user data. If user is not already saved in db, then user is * added in db, iff email is not already used, otherwise it sends an * UNAUTHORIZED status and redirect user to home page without authenticating * him/her. If it is all ok, then it authenticates user in spring security * and create cookie user. Then redirects authenticated user to home page * where user can access protected resources. * /*from w w w .j a v a2 s.com*/ * @param request * : instance of {@link HttpServletRequest} * @param response * : instance of {@link HttpServletResponse} * @return redirect to home page */ @RequestMapping(value = "/callback", method = RequestMethod.GET) public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) { String code = request.getParameter("code"); String token = request.getParameter("state"); String sessionStateToken = ""; if (request.getSession().getAttribute(SESSION_ATTR_STATE) != null) { sessionStateToken = request.getSession().getAttribute(SESSION_ATTR_STATE).toString(); } // compare state token in session and state token in response of google // if equals return to home // if not error page if ((code == null || token == null) && (!token.equals(sessionStateToken))) { logger.error("Error in google authentication flow"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return ""; } else { try { GoogleUser userInfo = auth.getUserInfoJson(code); response.setStatus(HttpServletResponse.SC_OK); request.getSession().setAttribute(GoogleAuthHelper.SESSION_GOOGLE_CHECK, "true"); return String.format( "redirect:/eauth/google?target=%s&OIDC_CLAIM_email=%s&OIDC_CLAIM_given_name=%s&OIDC_CLAIM_family_name=%s", URLEncoder.encode((String) request.getSession().getAttribute("redirect"), "UTF8"), userInfo.getEmail(), userInfo.getGivenName(), userInfo.getFamilyName()); } catch (IOException e) { logger.error("IOException .. Problem in reading user data.", e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } return "redirect:/"; }
From source file:com.wavemaker.runtime.FileController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String path = WMAppContext.getInstance().getAppContextRoot(); boolean isGzipped = false; boolean addExpiresTag = false; String reqPath = request.getRequestURI(); String contextPath = request.getContextPath(); reqPath = reqPath.replaceAll("%20", " "); reqPath = reqPath.replaceAll("//", "/"); // trim off the servlet name if (!contextPath.equals("") && reqPath.startsWith(contextPath)) { reqPath = reqPath.substring(reqPath.indexOf('/', 1)); }// ww w . j a va 2 s .co m if (reqPath.startsWith(WM_BUILD_GZIPPED_URL) || reqPath.startsWith(WM_GZIPPED_URL) || reqPath.equals(WM_BUILD_DOJO_JS_URL)) { isGzipped = true; addExpiresTag = true; reqPath += ".gz"; } else if (reqPath.startsWith(WM_BUILD_DOJO_THEMES_URL) || reqPath.startsWith(WM_BUILD_WM_THEMES_URL) || reqPath.startsWith(WM_BUILD_DOJO_FOLDER_URL) || reqPath.equals(WM_BOOT_URL) || reqPath.equals(WM_RUNTIME_LOADER_URL) || reqPath.startsWith(WM_IMAGE_URL) || reqPath.startsWith(WM_STUDIO_BUILD_URL)) { addExpiresTag = true; } else if (!reqPath.contains(WM_CONFIG_URL)) { throw new WMRuntimeException(MessageResource.STUDIO_UNKNOWN_LOCATION, reqPath, request.getRequestURI()); } File sendFile = null; if (!isGzipped && reqPath.lastIndexOf(".js") == reqPath.length() - 3) { sendFile = new File(path, reqPath + ".gz"); if (!sendFile.exists()) { sendFile = null; } else { isGzipped = true; } } if (sendFile == null) { sendFile = new File(path, reqPath); } if (DataServiceLoggers.fileControllerLogger.isDebugEnabled()) { DataServiceLoggers.fileControllerLogger .debug("FileController: " + sendFile.getAbsolutePath() + "\t (" + reqPath + ")"); } if (sendFile != null && !sendFile.exists()) { logger.debug("File " + reqPath + " not found in expected path: " + sendFile); handleError(response, "File " + reqPath + " not found in expected path: " + sendFile, HttpServletResponse.SC_NOT_FOUND); } else if (sendFile != null) { if (addExpiresTag) { // setting cache expire to one year. setCacheExpireDate(response, 365 * 24 * 60 * 60); } if (!isGzipped) { setContentType(response, sendFile); } else { response.setHeader("Content-Encoding", "gzip"); } OutputStream os = response.getOutputStream(); InputStream is = new FileInputStream(sendFile); if (reqPath.contains(WM_CONFIG_URL)) { StringBuilder content = new StringBuilder(IOUtils.toString(is)); int offset = ServerUtils.getServerTimeOffset(); int timeout = this.serviceResponse.getConnectionTimeout(); String timeStamp = "0"; File timeFile = new File(sendFile.getParent(), "timestamp.txt"); if (timeFile.exists()) { InputStream isTime = new FileInputStream(timeFile); timeStamp = IOUtils.toString(isTime); isTime.close(); } else { System.out.println("File timestamp.txt not found, using 0"); } content.append("\r\nwm.serverTimeOffset = ").append(offset).append(";"); content.append("\r\nwm.connectionTimeout = ").append(timeout).append(";"); content.append("\r\nwm.saveTimestamp = ").append(timeStamp).append(";"); String language = request.getHeader("accept-language"); if (language != null && language.length() > 0) { int index = language.indexOf(","); language = index == -1 ? language : language.substring(0, index); content.append("\r\nwm.localeString = '").append(language).append("';"); } File bootFile = new File(sendFile.getParent(), "boot.js"); if (bootFile.exists()) { InputStream is2 = new FileInputStream(bootFile); String bootString = IOUtils.toString(is2); bootString = bootString.substring(bootString.indexOf("*/") + 2); content.append(bootString); is2.close(); } else { System.out.println("Boot file not found"); } IOUtils.write(content.toString(), os); } else { IOUtils.copy(is, os); } os.close(); is.close(); } // we've already written our response return null; }
From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.info("POST request"); if (req.getParameter("url") == null) { logger.warn("URL parameter failed."); resp.sendError(HttpServletResponse.SC_NO_CONTENT, "URL parameter failed."); }/* ww w .j av a 2 s . co m*/ try { if (!authenticate(req, resp)) { logger.warn("Unauthorized request from " + req.getRemoteHost()); return; } PidCacheService cacheService = new PidCacheService(); String xmlOutput = null; if (logger.isDebugEnabled()) { logger.info("request pathInfo <" + req.getPathInfo() + ">"); } if (GwdgPidService.GWDG_PIDSERVICE_CREATE.equals(req.getPathInfo())) { xmlOutput = cacheService.create(req.getParameter("url")); } else if (GwdgPidService.GWDG_PIDSERVICE_EDIT.equals(req.getPathInfo())) { if (req.getParameter("pid") == null) { resp.sendError(HttpServletResponse.SC_NO_CONTENT, "PID parameter failed."); } xmlOutput = cacheService.update(req.getParameter("pid"), req.getParameter("url")); } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getPathInfo()); } resp.encodeRedirectURL(cacheService.getLocation()); resp.addHeader("Location", cacheService.getLocation()); resp.getWriter().append(xmlOutput); } catch (Exception e) { throw new ServletException("Error processing request", e); } }
From source file:nl.dtls.fairdatapoint.api.controller.DataAccessorControllerTest.java
/** * Check non existing Content.//from ww w . j av a 2 s .c o m * * @throws Exception */ @Test public void nonExistingContent() 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/gene-disease-association_lumc/dummy"); handler = handlerMapping.getHandler(request).getHandler(); handlerAdapter.handle(request, response, handler); assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); }
From source file:eu.dasish.annotation.backend.rest.AnnotationResource.java
/** * //from w w w . j a v a 2 s . c o m * @param externalIdentifier the UUID of an annotation. * @return the xml-element representing the annotation with "externalIdentifier" built up * from the "annotation" table and the corresponding junction tables. * @throws IOException if sending an error fails. */ @GET @Produces(MediaType.TEXT_XML) @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}") @Transactional(readOnly = true) public JAXBElement<Annotation> getAnnotation(@PathParam("annotationid") String externalIdentifier) throws IOException { Map params = new HashMap(); try { Annotation result = (Annotation) (new RequestWrappers(this)).wrapRequestResource(params, new GetAnnotation(), Resource.ANNOTATION, Access.READ, externalIdentifier); if (result != null) { return (new ObjectFactory()).createAnnotation(result); } else { return (new ObjectFactory()).createAnnotation(new Annotation()); } } catch (NotInDataBaseException e1) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage()); return (new ObjectFactory()).createAnnotation(new Annotation()); } catch (ForbiddenException e2) { httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage()); return (new ObjectFactory()).createAnnotation(new Annotation()); } }
From source file:com.cognitivabrasil.repositorio.web.FileControllerTest.java
@Test public void testGetThumbnail() throws IOException { HttpServletResponse response = new MockHttpServletResponse(); HttpServletResponse response2 = new MockHttpServletResponse(); FileController fileController = mockFiles(); // proves response and response2 are not comitted yet. Assert.assertFalse(response.isCommitted()); Assert.assertFalse(response2.isCommitted()); // tests id = null. fileController.getThumbnail(null, response); Assert.assertTrue(response.isCommitted()); assertThat(HttpServletResponse.SC_NOT_FOUND, equalTo(response.getStatus())); // tests id = 1 Long id = 1L;// w ww .j a v a 2 s. c om //proves response2 is only commited after flushbuffer. Assert.assertFalse(response2.isCommitted()); fileController.getThumbnail(id, response2); Assert.assertTrue(response2.isCommitted()); assertThat(HttpServletResponse.SC_CREATED, equalTo(response2.getStatus())); }