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:biz.taoconsulting.dominodav.methods.GET.java
/** * @see biz.taoconsulting.dominodav.methods.AbstractDAVMethod#action() *//*from w w w.j av a 2 s . co m*/ public void action() { InputStream stream = null; // The input stream coming from the resource OutputStream out = null; // The Servlet Response HttpServletResponse res = this.getResp(); try { // check if focused resource is a collection or a file resource... // collections are handled by propfind method // files / data will be send through the response stream writer... IDAVRepository rep = this.getRepository(); // Resource-Path is stripped by the repository name! // String curPath = (String) // this.getHeaderValues().get("resource-path"); // uri is the unique identifier on the host includes servlet and // repository but not server String curURI = (String) this.getHeaderValues().get("uri"); IDAVResource resource = rep.getResource(curURI); // Not ideal for browser access: we get the resource twice if (resource.isCollection()) { // LOGGER.info("Resource "+curURI +" is a collection"); PROPFIND p = new PROPFIND(); // Transfer the context if any p.setContext(this.getContext()); p.calledFromGET(); // LOGGER.info("After Called from GET"); p.process(this.getReq(), res, this.getRepository(), this.getLockManager()); // LOGGER.info("After Process "); } else { // LOGGER.info("Resource "+curURI +" is NOT a collection"); res.setHeader("Content-Type", resource.getMimeType()); res.setHeader("Pragma", "no-cache"); res.setHeader("Expires", "0"); res.setHeader("ETag", resource.getETag()); // TODO: Do we need content-disposition attachment or should it // be inline? res.setHeader("Content-disposition", "inline; filename*=" + ((IDAVAddressInformation) resource).getName()); // LOGGER.info("Set header finnish"); Long curLen = resource.getContentLength(); if (curLen != null && curLen.longValue() > 0) { // LOGGER.info("CurrLen is not null and positive="+ // curLen.toString()); res.setHeader("Content-Length", resource.getContentLength().toString()); } else { // LOGGER.info("CurrLen is null!!!"); } // Get the stream of the resource object and copy it into // the outputstream which is provided by the response object try { // LOGGER.info("Before resource getStream; class="+resource.getClass().toString()); stream = resource.getStream(); int read = 0; byte[] bytes = new byte[32768]; // ToDo is 32k a good // buffer? int totalread = 0; // TODO: Improve on this - is there a better way from input // to output stream? out = this.getOutputStream(); while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); totalread += read; } // Capture the result length // LOGGER.info("Before resource setContentLength"); res.setContentLength(totalread); // LOGGER.info("After resource setContentLength"); } catch (IOException iox) { this.setErrorMessage("Get method failed with:" + iox.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); LOGGER.error(iox); } } } catch (Exception exc) { LOGGER.error("Get method failed with:" + exc.getMessage(), exc); this.setErrorMessage("Get method failed with:" + exc.getMessage(), HttpServletResponse.SC_NOT_FOUND); } finally { // Close of all resources try { if (out != null) { out.flush(); out.close(); } if (stream != null) { stream.close(); } } catch (Exception e) { LOGGER.error("GET Object cleanup failed:" + e.getMessage(), e); } } }
From source file:flex.webtier.server.j2ee.MxmlServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try {/*from w w w . ja v a 2s. c om*/ // encoding must be set before any access to request parameters request.setCharacterEncoding("UTF-8"); MxmlContext context = new MxmlContext(); context.setRequest(request); context.setResponse(response); context.setServletContext(getServletContext()); context.setPageTitle(request.getServletPath()); setupMxmlContextKeys(getServletContext(), context, request); context.setDetectionSettings(DetectionSettingsFactory.getInstance(request.getContextPath())); context.setHistorySettings(HistorySettingsFactory.getInstance(request.getContextPath())); if (!ServiceFactory.getLicenseService().isMxmlCompileEnabled()) { response.sendError(481, "The current license does not support this feature."); ServiceFactory.getLogger().logError( "The current license does not support this feature. request=" + request.getServletPath()); return; } if (isObjectRequest(request)) { if (request.getParameter("w") != null) { context.setWidth(request.getParameter("w")); } else { context.setWidth("100%"); } if (request.getParameter("h") != null) { context.setHeight(request.getParameter("h")); } else { context.setHeight("100%"); } objectFilterChain.invoke(context); } else { PathResolver.setThreadLocalPathResolver(new ServletPathResolver(getServletContext())); flex2.compiler.common.PathResolver resolver = new flex2.compiler.common.PathResolver(); resolver.addSinglePathResolver( new flex.webtier.server.j2ee.ServletPathResolver(getServletContext())); resolver.addSinglePathResolver(LocalFilePathResolver.getSingleton()); resolver.addSinglePathResolver(URLPathResolver.getSingleton()); ThreadLocalToolkit.setPathResolver(resolver); // set up for localizing messages LocalizationManager localizationManager = new LocalizationManager(); localizationManager.addLocalizer(new XLRLocalizer()); localizationManager.addLocalizer(new ResourceBundleLocalizer()); ThreadLocalToolkit.setLocalizationManager(localizationManager); setupCompileEventLogger(context, request); setupSourceCodeLoader(context); filterChain.invoke(context); } } catch (FileNotFoundException fnfe) { // return an error page HttpCache.setCacheHeaders(false, 0, -1, response); response.sendError(HttpServletResponse.SC_NOT_FOUND, fnfe.getMessage()); if (logCompilerErrors) { ServiceFactory.getLogger().logError(fnfe.getMessage(), fnfe); } } catch (Throwable t) { // return an error page ServiceFactory.getLogger().logError("Unknown error " + request.getServletPath() + ": " + t.getMessage(), t); throw new ServletException(t); } finally { ServletUtils.clearThreadLocals(); } }
From source file:controller.IndicadoresMontoRestController.java
/** * * @param idi//from w w w . j av a 2s .c o m * @param request * @param response * @return JSON * Este metodo se encarga de generar la lista de entidades */ @RequestMapping(value = "/{idi}/municipios", method = RequestMethod.GET, produces = "application/json") public String getmJSON(@PathVariable("idi") String idi, HttpServletRequest request, HttpServletResponse response) { Gson JSON; List<DatosRegistrosMunicipios> listaFinal; List<Registros> listaRegistros; RegistrosDAO tablaRegistros; tablaRegistros = new RegistrosDAO(); /* *obtenemos la lista Registros */ try { listaRegistros = tablaRegistros.selectAllResgistrosByIdIndicador(idi); if (listaRegistros.isEmpty()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); Error e = new Error(); e.setTypeAndDescription("Warning", "No existen registros del indicador:" + idi); JSON = new Gson(); return JSON.toJson(e); } } catch (HibernateException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); Error e = new Error(); e.setTypeAndDescription("errorServer", ex.getMessage()); JSON = new Gson(); return JSON.toJson(e); } listaFinal = new ArrayList<>(); for (Registros r : listaRegistros) { listaFinal.add(new DatosRegistrosMunicipios(r.getIdRegistros(), r.getAnio(), r.getCantidad(), r.getIdMunicipio())); } Datos<DatosRegistrosMunicipios> datos = new Datos<>(); datos.setDatos(listaFinal); JSON = new Gson(); response.setStatus(HttpServletResponse.SC_OK); return JSON.toJson(datos); }
From source file:com.civilizer.web.handler.ResourceHttpRequestHandler.java
/** * Processes a resource request./* www . j ava2 s . co m*/ * <p>Checks for the existence of the requested resource in the configured list of locations. * If the resource does not exist, a {@code 404} response will be returned to the client. * If the resource exists, the request will be checked for the presence of the * {@code Last-Modified} header, and its value will be compared against the last-modified * timestamp of the given resource, returning a {@code 304} status code if the * {@code Last-Modified} value is greater. If the resource is newer than the * {@code Last-Modified} value, or the header is not present, the content resource * of the resource will be written to the response with caching headers * set to expire one year in the future. */ public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { checkRequest(request); prepareResponse(response); // check whether a matching resource exists Resource resource = getResource(request); if (resource == null) { logger.debug("No matching resource found - returning 404"); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // check the resource's media type MediaType mediaType = getMediaType(resource); if (mediaType != null) { if (logger.isDebugEnabled()) { logger.debug("Determined media type '" + mediaType + "' for " + resource); } } else { if (logger.isDebugEnabled()) { logger.debug("No media type found for " + resource + " - not sending a content-type header"); } } // header phase if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) { logger.debug("Resource not modified - returning 304"); return; } setHeaders(response, resource, mediaType); // content phase if (METHOD_HEAD.equals(request.getMethod())) { logger.trace("HEAD request - skipping content"); return; } writeContent(response, resource); }
From source file:com.novartis.pcs.ontology.rest.servlet.GraphServlet.java
private void graph(String termRefId, String mediaType, String orientation, String callback, HttpServletResponse response) {// w w w .ja v a 2 s .c o m GraphOrientation graphOrientation = GraphOrientation.TB; if (orientation != null) { try { graphOrientation = GraphOrientation.valueOf(orientation); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); return; } } if (mediaType == null) { response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); response.setContentLength(0); return; } try { String content = graphService.createGraph(termRefId, graphOrientation); // JSONP support if (callback != null) { StringBuilder builder = new StringBuilder(callback.length() + content.length() + 5); builder.append(callback); builder.append("(\""); builder.append(StringEscapeUtils.escapeJavaScript(content)); builder.append("\");"); content = builder.toString(); mediaType = "application/javascript"; } byte[] contentBytes = content.getBytes("UTF-8"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType(mediaType + ";charset=utf-8"); response.setHeader("Cache-Control", "public, max-age=0"); response.getOutputStream().write(contentBytes); } catch (EntityNotFoundException e) { log("Failed to find term with reference id: " + termRefId, e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); } catch (Exception e) { log("Failed to create graph for term " + termRefId, e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } }
From source file:com.openedit.modules.edit.BaseEditorModule.java
public void check404(WebPageRequest inReq) throws Exception { PageManager pageManager = getPageManager(); boolean exist = inReq.getPage().exists(); if (exist) {//from w w w.ja va2 s .c om Page page = inReq.getPage(); //If link does not exists. Then put a real welcome page on there so that fallback will work if (page.isFolder()) { String isVirtual = inReq.getPage().get("virtual"); if (Boolean.parseBoolean(isVirtual)) { return; } //Loop over the various starting pages. page = findWelcomePage(page); URLUtilities util = new URLUtilities(inReq.getRequest(), inReq.getResponse()); String requestedPath = util.getOriginalPath(); inReq.redirect(page.getPath()); } return; } PageStreamer streamer = inReq.getPageStreamer(); if (streamer != null) { streamer.getWebPageRequest().putPageValue("pathNotFound", inReq.getPath()); } String isVirtual = inReq.getPage().get("virtual"); if (Boolean.parseBoolean(isVirtual)) { return; } URLUtilities utils = (URLUtilities) inReq.getPageValue(PageRequestKeys.URL_UTILITIES); if (utils != null) { //redirecting only works relative to a webapp if (streamer != null) { streamer.getWebPageRequest().putPageValue("forcedDestinationPath", utils.requestPathWithArgumentsNoContext()); } } if (!inReq.getPage().isHtml()) { HttpServletResponse response = inReq.getResponse(); if (response != null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); inReq.setHasRedirected(true); return; } } if (inReq.getContentPage().getPath().equals(inReq.getPath())) { if (inReq.getPage().isHtml() && inReq.isEditable()) { String path = inReq.findValue("404wizardpage"); if (path == null) { path = "/system/nopagefound.html"; } Page wizard = pageManager.getPage(path); if (wizard.exists()) { inReq.getPageStreamer().include(wizard); inReq.setHasRedirected(true); return; } } //log.info( "Could not use add page wizard. 404 error on: " + inReq.getPath() ); String errorpage = inReq.getContentPage().getProperty("error404"); //"/error404.html"; errorpage = errorpage != null ? errorpage : ERROR404_HTML; Page p404 = pageManager.getPage(errorpage); if (p404.exists()) { HttpServletResponse response = inReq.getResponse(); if (response != null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } inReq.putProtectedPageValue("content", p404); //inReq.forward(p404.getPath()); return; } else { log.error("Could not report full 404 error on: " + inReq.getPath() + ". Make sure the 404 error page exists " + p404.getPath()); //other users will get the standard file not found error HttpServletResponse response = inReq.getResponse(); if (response != null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); inReq.setHasRedirected(true); } } } else { inReq.getWriter().write("404 on " + inReq.getPath()); inReq.getWriter().flush(); inReq.setHasRedirected(true); } }
From source file:com.novartis.pcs.ontology.rest.servlet.SubtermsServlet.java
private void serialize(String referenceId, boolean pending, HttpServletResponse response) { try {/*from ww w . ja v a2 s . c om*/ EnumSet<Status> statusSet = pending ? EnumSet.of(Status.PENDING, Status.APPROVED) : EnumSet.of(Status.APPROVED); Collection<Term> terms = termDAO.loadSubTermsByReferenceId(referenceId, statusSet); List<TermDTO> dtos = new ArrayList<TermDTO>(terms.size()); for (Term term : terms) { if (statusSet.contains(term.getStatus())) { dtos.add(new TermDTO(term)); } } if (!dtos.isEmpty()) { response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType(MEDIA_TYPE_JSON + ";charset=utf-8"); response.setHeader("Cache-Control", "public, max-age=0"); // As per jackson javadocs - Encoding will be UTF-8 mapper.writeValue(response.getOutputStream(), dtos); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); } } catch (Exception e) { log("Failed to serialize synonyms to JSON", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } }
From source file:grails.plugin.errorpagesfix.PatchedErrorHandlingServlet.java
private void renderDefaultResponse(HttpServletResponse response, int statusCode, String title, String text) throws IOException { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentType(TEXT_HTML); Writer writer = response.getWriter(); writer.write("<HTML>\n<HEAD>\n<TITLE>Error " + statusCode + " - " + title); writer.write("</TITLE>\n<BODY>\n<H2>Error " + statusCode + " - " + title + ".</H2>\n"); writer.write(text + "<BR/>"); for (int i = 0; i < 20; i++) { writer.write("\n<!-- Padding for IE -->"); }//from w w w .j a v a2s .c om writer.write("\n</BODY>\n</HTML>\n"); writer.flush(); }
From source file:org.wiredwidgets.cow.server.web.ProcessInstancesController.java
/** * Retrieve a specific process instance by its ID * * Current JBPM implementation assigns processInstanceId using * the format {processKey}.{uniqueNumber} * @param id the process key. If the key includes "/" character(s), the key must be doubly URL encoded. I.e. "/" becomes "%252F" * @param ext the numeric extension of the process instance, or the wildcard "*" for all instances * @param response//w w w . ja va2s. com * @return a ProcessInstance object, if the extension specifies a single instance. If the extension is the "*" wildcard, * then the return value will be an ProcessInstances object. If a single ProcessInstance is requested and it does not exist, * a 404 response will be returned. */ @RequestMapping(value = "/active/{id}.{ext}", method = RequestMethod.GET) @ResponseBody public Object getProcessInstance(@PathVariable("id") String id, @PathVariable("ext") String ext, HttpServletResponse response) { if (ext.equals("*")) { ProcessInstances pi = new ProcessInstances(); // note: decoding is applied to the id primarily to handle possible "/" characters pi.getProcessInstances().addAll(processInstanceService.findProcessInstancesByKey(decode(id))); return pi; } else { //org.wiredwidgets.cow.server.api.service.ProcessInstance instance = processInstanceService.getProcessInstance(id + '.' + ext); org.wiredwidgets.cow.server.api.service.ProcessInstance instance = processInstanceService .getProcessInstance(ext); if (instance == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404 } return instance; } }
From source file:edu.wisc.my.redirect.PortalUrlRedirectController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { final String serverName = request.getServerName(); final PortalUrl portalUrl = this.portalUrlProvider.getPortalUrl(serverName); if (this.portletFunctionalName != null) { portalUrl.setTargetPortlet(this.portletFunctionalName); }//ww w. ja va 2s . co m if (this.tabIndex != null) { portalUrl.setTabIndex(this.tabIndex); } //If strict param matching only run if the request parameter keyset matches the mapped parameter keyset final Set<?> requestParameterKeys = request.getParameterMap().keySet(); if (this.strictParameterMatching && !requestParameterKeys.equals(this.parameterMappings.keySet())) { if (this.logger.isInfoEnabled()) { this.logger.info("Sending not found error, requested parameter key set " + requestParameterKeys + " does not match mapped parameter key set " + this.parameterMappings.keySet()); } response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } //Map static parameters logger.debug("Mapping " + staticParameters.size() + " static parameters"); for (final Map.Entry<String, List<String>> parameterMappingEntry : this.staticParameters.entrySet()) { final String name = parameterMappingEntry.getKey(); final List<String> values = parameterMappingEntry.getValue(); if (this.logger.isDebugEnabled()) { this.logger.debug("Adding static parameter '" + name + "' with values: " + values); } portalUrl.setParameter(name, values.toArray(new String[values.size()])); } //Map request parameters logger.debug("Mapping " + parameterMappings.entrySet().size() + " request parameters"); for (final Map.Entry<String, Set<String>> parameterMappingEntry : this.parameterMappings.entrySet()) { final String name = parameterMappingEntry.getKey(); logger.debug("Mapping parameter " + name); final String[] values = request.getParameterValues(name); if (values != null) { for (final String mappedName : parameterMappingEntry.getValue()) { if (this.logger.isDebugEnabled()) { this.logger.debug("Mapping parameter '" + name + "' to portal parameter '" + mappedName + "' with values: " + Arrays.asList(values)); } portalUrl.setParameter(mappedName, values); } //Add any conditional parameters for the URL parameter final Map<String, List<String>> conditionalParameters = this.conditionalParameterMappings.get(name); if (conditionalParameters != null) { for (final Map.Entry<String, List<String>> conditionalParameterEntry : conditionalParameters .entrySet()) { final String condName = conditionalParameterEntry.getKey(); final List<String> condValues = conditionalParameterEntry.getValue(); if (this.logger.isDebugEnabled()) { this.logger.debug( "Adding conditional parameter '" + condName + "' with values: " + condValues); } portalUrl.setParameter(condName, condValues.toArray(new String[condValues.size()])); } } } else if (this.logger.isDebugEnabled()) { this.logger.debug( "Skipping mapped parameter '" + name + "' since it was not specified on the original URL"); } } //Set public based on if remoteUser is set final String remoteUser = request.getRemoteUser(); final boolean isAuthenticated = StringUtils.isNotBlank(remoteUser); portalUrl.setPublic(!isAuthenticated); if (this.windowState != null) { portalUrl.setWindowState(this.windowState); } if (this.portletMode != null) { portalUrl.setWindowState(this.portletMode); } portalUrl.setType(RequestType.ACTION); final String redirectUrl = portalUrl.toString(); if (this.logger.isInfoEnabled()) { this.logger.info("Redirecting to: " + redirectUrl); } return new ModelAndView(new RedirectView(redirectUrl, false)); }