List of usage examples for org.springframework.core.io Resource exists
boolean exists();
From source file:org.springframework.data.hadoop.admin.web.WorkflowController.java
@RequestMapping(value = "/workflows/**", method = RequestMethod.GET) public String get(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize, @ModelAttribute("date") Date date, Errors errors) throws Exception { list(model, startFile, pageSize);/*w w w. j a va 2s. c o m*/ String path = request.getPathInfo().substring("/workflows/".length()); Resource file = workflowService.getResource(path); if (file == null || !file.exists()) { errors.reject("file.download.missing", new Object[] { path }, "File download failed for missing file at path=" + HtmlUtils.htmlEscape(path)); return "workflows"; } response.setContentType("application/octet-stream"); try { FileCopyUtils.copy(file.getInputStream(), response.getOutputStream()); } catch (IOException e) { errors.reject("file.download.failed", new Object[] { path }, "File download failed for path=" + HtmlUtils.htmlEscape(path)); logger.info("File download failed for path=" + path, e); return "workflows"; } return null; }
From source file:org.springframework.data.hadoop.impala.r.RCommands.java
@CliCommand(value = { PREFIX + "script" }, help = "Executes a R script") public String script( @CliOption(key = { "", "location" }, mandatory = true, help = "Script location") String location, @CliOption(key = { "args" }, mandatory = false, help = "Script arguments") String args) { if (!new File(cmd).exists()) { return "Cannot find R command [" + cmd + "]"; }//from ww w .j a v a 2s .c o m Resource resource = resourceResolver.getResource(fixLocation(location)); if (!resource.exists()) { return "No resource found at " + location; } String uri = location; try { uri = resource.getFile().getAbsolutePath(); } catch (IOException ex) { // ignore - we'll use location } Process process; List<String> cmds = new ArrayList<String>(); cmds.add(cmd); cmds.add(uri); if (StringUtils.hasText(args)) { cmds.addAll(Arrays.asList(StringUtils.tokenizeToStringArray(args, " "))); } BufferedReader output = null; try { process = new ProcessBuilder(cmds).directory(wkdir).redirectErrorStream(true).start(); output = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = output.readLine()) != null) { System.out.println(line); } int code = process.waitFor(); return "R script executed with exit code - " + code; } catch (Exception ex) { return "R script execution failed - " + ex; } finally { IOUtils.closeQuietly(output); } }
From source file:org.springframework.data.mongodb.core.MongoTemplate.java
protected String replaceWithResourceIfNecessary(String function) { String func = function;//from w w w . j ava 2 s .c o m if (this.resourceLoader != null && ResourceUtils.isUrl(function)) { Resource functionResource = resourceLoader.getResource(func); if (!functionResource.exists()) { throw new InvalidDataAccessApiUsageException(String.format("Resource %s not found!", function)); } try { return new Scanner(functionResource.getInputStream()).useDelimiter("\\A").next(); } catch (IOException e) { throw new InvalidDataAccessApiUsageException( String.format("Cannot read map-reduce file %s!", function), e); } } return func; }
From source file:org.springframework.extensions.webscripts.ClassPathStore.java
public boolean hasDocument(String documentPath) { boolean exists = false; Resource document = this.getDocumentResource(documentPath); if (document != null) { exists = document.exists(); }/*from w ww . j a v a 2 s .c o m*/ return exists; }
From source file:org.springframework.extensions.webscripts.ClassPathStore.java
public InputStream getDocument(String documentPath) throws IOException { Resource document = this.getDocumentResource(documentPath); if (document == null || !document.exists()) { throw new IOException("Document " + documentPath + " does not exist within store " + getBasePath()); }/* ww w .j av a2s. co m*/ if (logger.isTraceEnabled()) logger.trace("getDocument: documentPath: " + documentPath + " , storePath: " + document.getURL().toExternalForm()); return document.getInputStream(); }
From source file:org.springframework.extensions.webscripts.ClassPathStoreResourceResolver.java
/** * Retrieves a resource for a given location * /*from w ww . j ava 2s . co m*/ * This method performs a robust lookup, first checking the servlet context for the resource. This * will resolve simple class files and other simple class path elements. These are physical file * elements accessible by the resource loader. If nothing is found, the JAR files in the * servlet context are then consulted. This lookup may result in a URL to an element inside of a * JAR file. * * If a resource cannot ultimately be found, null is returned. * * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResource(java.lang.String) */ public Resource getResource(String location) { Resource resource = null; // look for classes Resource r = super.getResource(location); if (r != null && r.exists()) { resource = r; } else { // see if this resource is in a JAR file URL resourceUrl = ClassUtils.getDefaultClassLoader().getResource(location); if (resourceUrl != null) { r = new UrlInputStreamResource(resourceUrl); if (r.exists()) { resource = r; } } } return resource; }
From source file:org.springframework.extensions.webscripts.servlet.mvc.ResourceController.java
/** * Dispatches to the resource with the given path * //from w w w .ja va2s.c o m * @param path the path * @param request the request * @param response the response */ public boolean dispatchResource(final String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final boolean debug = logger.isDebugEnabled(); if (debug) logger.debug("Attemping to dispatch resource: " + path); boolean resolved = false; { // check JAR files URL resourceUrl = ClassUtils.getDefaultClassLoader().getResource("META-INF/" + path); if (resourceUrl != null) { if (debug) logger.debug("...dispatching resource from JAR location: " + resourceUrl); // attempt to stream back try { commitResponse(path, resourceUrl, response); resolved = true; } catch (IOException ioe) { logger.info(ioe.getMessage()); if (debug) ioe.printStackTrace(); } } } if (!resolved) { // look up the resource in the resource provider // (application context resources / classpath) // check the classpath Resource r = getApplicationContext().getResource("classpath*:" + path); if (r != null && r.exists()) { URL resourceUrl = r.getURL(); if (debug) logger.debug("...dispatching resource from classpath location: " + resourceUrl); // stream back resource try { commitResponse(path, resourceUrl, response); resolved = true; } catch (IOException ioe) { logger.info(ioe.getMessage()); if (debug) ioe.printStackTrace(); } } } if (!resolved) { // serve back the resource from the web application (if it exists) ServletContextResource resource = new ServletContextResource(getServletContext(), "/" + path); if (resource.exists()) { // dispatch to resource if (debug) logger.debug("...dispatching resource from web application ServletContext."); commitResponse(path, resource, request, response); resolved = true; } } if (!resolved && defaultUrl != null) { if (debug) logger.debug("...handing off to Spring resource servlet: " + defaultUrl + "/" + path); // try to hand off to a default servlet context (compatibility with Spring JS resource servlet) // use a forward here because the new servlet context may be different than the current servlet context RequestDispatcher rd = this.getServletContext().getRequestDispatcher(defaultUrl + "/" + path); rd.forward(request, response); resolved = true; } return resolved; }
From source file:org.springframework.flex.core.MessageBrokerFactoryBean.java
private void setupInternalPathResolver() { this.messageBroker.setInternalPathResolver(new MessageBroker.InternalPathResolver() { public InputStream resolve(String filename) { try { Resource resource = MessageBrokerFactoryBean.this.resourceLoader .getResource(FLEXDIR + filename); if (resource.exists()) { return resource.getInputStream(); } else { return null; }//ww w.j a v a2s. c o m } catch (IOException e) { throw new IllegalStateException( "Could not resolve Flex internal resource at: " + FLEXDIR + filename); } } }); }
From source file:org.springframework.flex.core.MessageBrokerFactoryBean.java
private void setupExternalPathResolver() { BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(this.messageBroker); wrapper.setPropertyValue("externalPathResolver", new MessageBroker.InternalPathResolver() { public InputStream resolve(String filename) throws IOException { try { Resource resource = MessageBrokerFactoryBean.this.resourceLoader.getResource(filename); if (resource.exists()) { return resource.getInputStream(); } else { return null; }/*from w w w.ja va 2s .c om*/ } catch (IOException e) { throw new IllegalStateException("Could not resolve Flex internal resource at: " + filename); } } }); }
From source file:org.springframework.integration.expression.ReloadableResourceBundleExpressionSource.java
/** * Refresh the PropertiesHolder for the given bundle filename. * The holder can be <code>null</code> if not cached before, or a timed-out cache entry * (potentially getting re-validated against the current last-modified timestamp). * @param filename the bundle filename (basename + Locale) * @param propHolder the current PropertiesHolder for the bundle *//*from w ww .ja va2 s.co m*/ private PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) { long refreshTimestamp = (this.cacheMillis < 0) ? -1 : System.currentTimeMillis(); Resource resource = this.resourceLoader.getResource(filename + PROPERTIES_SUFFIX); if (!resource.exists()) { resource = this.resourceLoader.getResource(filename + XML_SUFFIX); } if (resource.exists()) { long fileTimestamp = -1; if (this.cacheMillis >= 0) { // Last-modified timestamp of file will just be read if caching with timeout. try { fileTimestamp = resource.lastModified(); if (propHolder != null && propHolder.getFileTimestamp() == fileTimestamp) { if (logger.isDebugEnabled()) { logger.debug("Re-caching properties for filename [" + filename + "] - file hasn't been modified"); } propHolder.setRefreshTimestamp(refreshTimestamp); return propHolder; } } catch (IOException ex) { // Probably a class path resource: cache it forever. if (logger.isDebugEnabled()) { logger.debug(resource + " could not be resolved in the file system - assuming that is hasn't changed", ex); } fileTimestamp = -1; } } try { Properties props = loadProperties(resource, filename); propHolder = new PropertiesHolder(props, fileTimestamp); } catch (IOException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not parse properties file [" + resource.getFilename() + "]", ex); } // Empty holder representing "not valid". propHolder = new PropertiesHolder(); } } else { // Resource does not exist. if (logger.isDebugEnabled()) { logger.debug("No properties file found for [" + filename + "] - neither plain properties nor XML"); } // Empty holder representing "not found". propHolder = new PropertiesHolder(); } propHolder.setRefreshTimestamp(refreshTimestamp); this.cachedProperties.put(filename, propHolder); return propHolder; }