List of usage examples for org.springframework.core.io Resource getFile
File getFile() throws IOException;
From source file:org.springframework.cloud.deployer.thin.ThinJarAppWrapper.java
public ThinJarAppWrapper(Resource resource, String name, String[] profiles) { this.resource = resource; this.name = name; this.profiles = profiles; try {/* ww w . j av a 2 s .com*/ this.id = DigestUtils .md5DigestAsHex(resource.getFile().getAbsolutePath().getBytes(Charset.forName("UTF-8"))); } catch (IOException e) { throw new IllegalArgumentException("Not a valid file resource"); } }
From source file:org.springframework.context.expression.ApplicationContextExpressionTests.java
@Test public void resourceInjection() throws IOException { System.setProperty("logfile", "do_not_delete_me.txt"); try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext( ResourceInjectionBean.class)) { ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.class); Resource resource = new ClassPathResource("do_not_delete_me.txt"); assertEquals(resource, resourceInjectionBean.resource); assertEquals(resource.getURL(), resourceInjectionBean.url); assertEquals(resource.getURI(), resourceInjectionBean.uri); assertEquals(resource.getFile(), resourceInjectionBean.file); assertArrayEquals(FileCopyUtils.copyToByteArray(resource.getInputStream()), FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream)); assertEquals(FileCopyUtils.copyToString(new EncodedResource(resource).getReader()), FileCopyUtils.copyToString(resourceInjectionBean.reader)); } finally {/*from w w w.j av a 2 s. c om*/ System.getProperties().remove("logfile"); } }
From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java
/** * Find all resources in the file system that match the given location pattern * via the Ant-style PathMatcher./*w ww. j a v a2 s .c o m*/ * @param rootDirResource the root directory as Resource * @param subPattern the sub pattern to match (below the root directory) * @return a mutable Set of matching Resource instances * @throws IOException in case of I/O errors * @see #retrieveMatchingFiles * @see org.springframework.util.PathMatcher */ protected Set<Resource> doFindPathMatchingFileResources(Resource rootDirResource, String subPattern) throws IOException { File rootDir; try { rootDir = rootDirResource.getFile().getAbsoluteFile(); } catch (IOException ex) { if (logger.isWarnEnabled()) { logger.warn("Cannot search for matching files underneath " + rootDirResource + " because it does not correspond to a directory in the file system", ex); } return Collections.emptySet(); } return doFindMatchingFileSystemResources(rootDir, subPattern); }
From source file:org.springframework.data.hadoop.admin.service.BaseFileService.java
public List<FileInfo> getFiles(String pattern) { ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); List<Resource> resources = new ArrayList<Resource>(); if (!pattern.startsWith("/")) { pattern = "/" + outputDir.getAbsolutePath() + "/" + pattern; }//from ww w .ja v a 2 s . c om if (!pattern.startsWith("file:")) { pattern = "file:///" + pattern; } try { resources = Arrays.asList(resolver.getResources(pattern)); } catch (IOException e) { logger.debug("Cannot locate files " + pattern, e); return new ArrayList<FileInfo>(); } List<FileInfo> files = new ArrayList<FileInfo>(); for (Resource resource : resources) { File file; try { file = resource.getFile(); if (file.isFile()) { FileInfo info = new FileInfo(extractPath(file)); files.add(info); } } catch (IOException e) { logger.debug("Cannot locate file " + resource, e); } } Collections.sort(files); return new ArrayList<FileInfo>(files); }
From source file:org.springframework.data.hadoop.admin.service.BaseFileService.java
public int delete(String pattern) throws IOException { ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); if (!pattern.startsWith("/")) { pattern = "/" + outputDir.getAbsolutePath() + "/" + pattern; }//from ww w . j a v a 2 s . c om if (!pattern.startsWith("file:")) { pattern = "file:///" + pattern; } Resource[] resources = resolver.getResources(pattern); int count = 0; for (Resource resource : resources) { File file = resource.getFile(); fileRemover.beforeRemove(file); if (file.isFile()) { count++; logger.info("removing file:" + file.getAbsolutePath()); FileUtils.deleteQuietly(file); } } return count; }
From source file:org.springframework.data.hadoop.admin.util.HadoopWorkflowUtils.java
/** * get workflow descriptor file name/*from w ww . ja v a 2s.c o m*/ * * @param artifacts workflow artificats * * @return The workflow descriptor file name * @throws SpringHadoopAdminWorkflowException */ public static String getWorkflowDescriptor(final WorkflowArtifacts artifacts) throws SpringHadoopAdminWorkflowException { if (artifacts == null) { logger.warn("workflow artifacts is null"); throw new SpringHadoopAdminWorkflowException("workflow artifacts is null"); } String workflowDescriptor = null; try { Resource resource = artifacts.getWorkflowDescriptor(); if (resource == null) { throw new SpringHadoopAdminWorkflowException("workflow's descriptor is null"); } File file = resource.getFile(); if (file == null) { throw new SpringHadoopAdminWorkflowException("workflow's descriptor is null"); } workflowDescriptor = file.getAbsolutePath(); } catch (IOException e) { throw new SpringHadoopAdminWorkflowException("IO error when trying to get workflow's descriptor."); } return workflowDescriptor; }
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 2 s . 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.extensions.webscripts.ClassPathStore.java
public void init() { // wrap the application context resource resolver with our own this.resolver = new ClassPathStoreResourceResolver(applicationContext); // check if there are any resources that live under this path // this is valid for read-only classpaths (class files + JAR file contents) try {//from w ww .ja v a 2 s .c o m Resource[] resources = resolver.getResources("classpath*:" + classPath + "/*"); if (resources.length != 0) { exists = true; } else { resources = resolver.getResources("classpath*:" + classPath + "/**/*"); exists = (resources.length != 0); } if (exists) { // NOTE: Locate root of web script store // NOTE: Following awkward approach is used to mirror lookup of web scripts within store. This // ensures root paths match. try { List<String> storeDirList = null; // Process each root resource - there may be several as the classpath* could match // multiple location that each contain the configured path. Resource rootResource = null; resources = resolver.getResources("classpath*:" + classPath + "*"); if (resources.length == 0) { // the resolver may not be able to visit root folders using the pattern // so get contents and manually walk up path to resolve a root // this only appears to occur for a JBoss VFS directory outside of the war file location resources = resolver.getResources("classpath*:" + classPath + "/*"); if (resources.length != 0) { String externalForm = resources[0].getURL().toExternalForm(); externalForm = externalForm.substring(0, externalForm.lastIndexOf('/')); if (externalForm.endsWith(classPath)) { storeDirList = new ArrayList<String>(1); storeDirList.add(externalForm); } } } else { storeDirList = new ArrayList<String>(resources.length); for (Resource resource : resources) { String externalForm = resource.getURL().toExternalForm(); if (externalForm.endsWith(classPath) || externalForm.endsWith(classPath + "/")) { // we've found the right resource, let's now bind using string constructor // so that Spring 3 will correctly create relative paths String directoryPath = resource.getFile().getAbsolutePath(); if (resource.getFile().isDirectory() && !directoryPath.endsWith("/")) { directoryPath += "/"; } if (new FileSystemResource(directoryPath).exists()) { // retrieve file system directory storeDirList.add(resource.getFile().toURI().toURL().toExternalForm()); } } } } if (storeDirList != null && storeDirList.size() != 0) { this.storeDirs = storeDirList.toArray(new String[storeDirList.size()]); } } catch (IOException ioErr) { // unable to resolve a storeDir - this is expected for certain protocols such as "vfszip" // it is not critical and those protocols don't require it during path resolution later if (logger.isDebugEnabled()) logger.debug("Unable to resolve storeDir for base path " + classPath); } } } catch (IOException ioe) { throw new WebScriptException("Failed to initialise Web Script Store classpath: " + classPath, ioe); } if (!exists && mustExist) { throw new WebScriptException( "Web Script Store classpath:" + classPath + " must exist; it was not found"); } }
From source file:org.springframework.http.codec.ResourceHttpMessageWriter.java
private static Optional<Mono<Void>> zeroCopy(Resource resource, @Nullable ResourceRegion region, ReactiveHttpOutputMessage message, Map<String, Object> hints) { if (message instanceof ZeroCopyHttpOutputMessage && resource.isFile()) { try {//from w w w. ja v a 2 s .com File file = resource.getFile(); long pos = region != null ? region.getPosition() : 0; long count = region != null ? region.getCount() : file.length(); if (logger.isDebugEnabled()) { String formatted = region != null ? "region " + pos + "-" + (count) + " of " : ""; logger.debug(Hints.getLogPrefix(hints) + "Zero-copy " + formatted + "[" + resource + "]"); } return Optional.of(((ZeroCopyHttpOutputMessage) message).writeWith(file, pos, count)); } catch (IOException ex) { // should not happen } } return Optional.empty(); }