List of usage examples for org.springframework.core.io Resource getFile
File getFile() throws IOException;
From source file:org.red5.server.persistence.FilePersistence.java
/** * Remove empty dirs/*from w ww. ja va2 s . c o m*/ * @param base Base directory */ protected void checkRemoveEmptyDirectories(String base) { if (!checkForEmptyDirectories) { return; } String dir; Resource resFile = resources.getResource(base.substring(0, base.lastIndexOf('/'))); try { dir = resFile.getFile().getAbsolutePath(); } catch (IOException err) { return; } while (!dir.equals(rootDir)) { File fp = new File(dir); if (!fp.isDirectory()) { // This should never happen break; } if (fp.list().length != 0) { // Directory is not empty break; } if (!fp.delete()) { // Could not remove directory break; } // Move up one directory dir = fp.getParent(); } }
From source file:org.red5.server.persistence.FilePersistence.java
/** {@inheritDoc} */ @Override/*from w w w . j a va 2 s . c om*/ public boolean remove(String name) { super.remove(name); String filename = path + '/' + name + extension; Resource resFile = resources.getResource(filename); if (!resFile.exists()) { // File already deleted return true; } try { boolean result = resFile.getFile().delete(); if (result) { checkRemoveEmptyDirectories(filename); } return result; } catch (IOException err) { return false; } }
From source file:org.red5.server.stream.ServerStream.java
/** {@inheritDoc} */ public void saveAs(String name, boolean isAppend) throws IOException, ResourceNotFoundException, ResourceExistException { try {//ww w .j av a2 s . c o m IScope scope = getScope(); IStreamFilenameGenerator generator = (IStreamFilenameGenerator) ScopeUtils.getScopeService(scope, IStreamFilenameGenerator.class, DefaultStreamFilenameGenerator.class); String filename = generator.generateFilename(scope, name, ".flv", GenerationType.RECORD); Resource res = scope.getContext().getResource(filename); if (!isAppend) { if (res.exists()) { // Per livedoc of FCS/FMS: // When "live" or "record" is used, // any previously recorded stream with the same stream URI is deleted. if (!res.getFile().delete()) throw new IOException("file could not be deleted"); } } else { if (!res.exists()) { // Per livedoc of FCS/FMS: // If a recorded stream at the same URI does not already exist, // "append" creates the stream as though "record" was passed. isAppend = false; } } if (!res.exists()) { // Make sure the destination directory exists try { String path = res.getFile().getAbsolutePath(); int slashPos = path.lastIndexOf(File.separator); if (slashPos != -1) { path = path.substring(0, slashPos); } File tmp = new File(path); if (!tmp.isDirectory()) { tmp.mkdirs(); } } catch (IOException err) { log.error("Could not create destination directory.", err); } res = scope.getResource(filename); } if (!res.exists()) { if (!res.getFile().canWrite()) { log.warn("File cannot be written to " + res.getFile().getCanonicalPath()); } res.getFile().createNewFile(); } FileConsumer fc = new FileConsumer(scope, res.getFile()); Map<Object, Object> paramMap = new HashMap<Object, Object>(); if (isAppend) { paramMap.put("mode", "append"); } else { paramMap.put("mode", "record"); } if (null == recordPipe) { recordPipe = new InMemoryPushPushPipe(); } recordPipe.subscribe(fc, paramMap); recordingFilename = filename; } catch (IOException e) { log.warn("Save as exception", e); } }
From source file:org.springframework.batch.admin.service.LocalFileService.java
private List<FileInfo> getFiles(String pattern) { ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); List<Resource> resources = new ArrayList<Resource>(); if (!pattern.startsWith("/")) { pattern = "/" + outputDir.getAbsolutePath() + "/" + pattern; }//from w ww . j a v a 2 s . c o m 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.batch.admin.service.LocalFileService.java
public int delete(String pattern) throws IOException { ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); if (!pattern.startsWith("/")) { pattern = "/" + outputDir.getAbsolutePath() + "/" + pattern; }/* w ww. j a v a 2s . c o m*/ if (!pattern.startsWith("file:")) { pattern = "file:///" + pattern; } Resource[] resources = resolver.getResources(pattern); int count = 0; for (Resource resource : resources) { File file = resource.getFile(); if (file.isFile()) { count++; FileUtils.deleteQuietly(file); } } return count; }
From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java
@Test public void testNonExistantResource() throws Exception { Resource doesntExist = mock(Resource.class); when(doesntExist.getFile()).thenReturn(File.createTempFile("arbitrary", null)); when(doesntExist.exists()).thenReturn(false); writer.setResource(doesntExist);//from w ww .ja va 2s . c om try { writer.open(executionContext); fail(); } catch (IllegalStateException e) { assertEquals("Output resource must exist", e.getMessage()); } }
From source file:org.springframework.cloud.config.server.support.AbstractScmAccessor.java
private List<String> matchingDirectories(File dir, String value) { List<String> output = new ArrayList<String>(); try {/* ww w. j av a2 s . c o m*/ PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( this.resourceLoader); String path = new File(dir, value).toURI().toString(); for (Resource resource : resolver.getResources(path)) { if (resource.getFile().isDirectory()) { output.add(resource.getURI().toString()); } } } catch (IOException e) { } return output; }
From source file:org.springframework.cloud.dataflow.app.launcher.ModuleLauncher.java
public void launchAggregatedModules(List<ModuleLaunchRequest> moduleLaunchRequests, Map<String, String> aggregateArgs) { try {/*from w w w . j a va2 s .c om*/ List<String> mainClassNames = new ArrayList<>(); LinkedHashSet<URL> jarURLs = new LinkedHashSet<>(); List<String> seenArchives = new ArrayList<>(); final List<String[]> arguments = new ArrayList<>(); final ClassLoader classLoader; if (!(aggregateArgs.containsKey(EXCLUDE_DEPENDENCIES_ARG) || aggregateArgs.containsKey(INCLUDE_DEPENDENCIES_ARG))) { for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) { Resource resource = resolveModule(moduleLaunchRequest.getModule()); JarFileArchive jarFileArchive = new JarFileArchive(resource.getFile()); jarURLs.add(jarFileArchive.getUrl()); for (Archive archive : jarFileArchive.getNestedArchives(ArchiveMatchingEntryFilter.FILTER)) { // avoid duplication based on unique JAR names String urlAsString = archive.getUrl().toString(); String jarNameWithExtension = urlAsString.substring(0, urlAsString.lastIndexOf("!/")); String jarNameWithoutExtension = jarNameWithExtension .substring(jarNameWithExtension.lastIndexOf("/") + 1); if (!seenArchives.contains(jarNameWithoutExtension)) { seenArchives.add(jarNameWithoutExtension); jarURLs.add(archive.getUrl()); } } mainClassNames.add(jarFileArchive.getMainClass()); arguments.add(toArgArray(moduleLaunchRequest.getArguments())); } classLoader = ClassloaderUtils.createModuleClassloader(jarURLs.toArray(new URL[jarURLs.size()])); } else { // First, resolve modules and extract main classes - while slightly less efficient than just // doing the same processing after resolution, this ensures that module artifacts are processed // correctly for extracting their main class names. It is not possible in the general case to // identify, after resolution, whether a resource represents a module artifact which was part of the // original request or not. We will include the first module as root and the next as direct dependencies Coordinates root = null; ArrayList<Coordinates> includeCoordinates = new ArrayList<>(); for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) { Coordinates moduleCoordinates = toCoordinates(moduleLaunchRequest.getModule()); if (root == null) { root = moduleCoordinates; } else { includeCoordinates.add(toCoordinates(moduleLaunchRequest.getModule())); } Resource moduleResource = resolveModule(moduleLaunchRequest.getModule()); JarFileArchive moduleArchive = new JarFileArchive(moduleResource.getFile()); mainClassNames.add(moduleArchive.getMainClass()); arguments.add(toArgArray(moduleLaunchRequest.getArguments())); } for (String include : StringUtils .commaDelimitedListToStringArray(aggregateArgs.get(INCLUDE_DEPENDENCIES_ARG))) { includeCoordinates.add(toCoordinates(include)); } // Resolve all artifacts - since modules have been specified as direct dependencies, they will take // precedence in the resolution order, ensuring that the already resolved artifacts will be returned as // part of the response. Resource[] libraries = moduleResolver.resolve(root, includeCoordinates.toArray(new Coordinates[includeCoordinates.size()]), StringUtils.commaDelimitedListToStringArray(aggregateArgs.get(EXCLUDE_DEPENDENCIES_ARG))); for (Resource library : libraries) { jarURLs.add(library.getURL()); } classLoader = new URLClassLoader(jarURLs.toArray(new URL[jarURLs.size()])); } final List<Class<?>> mainClasses = new ArrayList<>(); for (String mainClass : mainClassNames) { mainClasses.add(ClassUtils.forName(mainClass, classLoader)); } Runnable moduleAggregatorRunner = new ModuleAggregatorRunner(classLoader, mainClasses, toArgArray(aggregateArgs), arguments); Thread moduleAggregatorRunnerThread = new Thread(moduleAggregatorRunner); moduleAggregatorRunnerThread.setContextClassLoader(classLoader); moduleAggregatorRunnerThread.setName(MODULE_AGGREGATOR_RUNNER_THREAD_NAME); moduleAggregatorRunnerThread.start(); } catch (Exception e) { throw new RuntimeException("failed to start aggregated modules: " + StringUtils.collectionToCommaDelimitedString(moduleLaunchRequests), e); } }
From source file:org.springframework.cloud.dataflow.app.launcher.ModuleLauncher.java
private void launchModule(String module, String[] args) { try {/*from ww w . j a v a2s .c o m*/ Resource resource = resolveModule(module); JarFileArchive jarFileArchive = new JarFileArchive(resource.getFile()); ModuleJarLauncher jarLauncher = new ModuleJarLauncher(jarFileArchive); jarLauncher.launch(args); } catch (IOException e) { throw new RuntimeException("failed to launch module: " + module, e); } }
From source file:org.springframework.cloud.dataflow.app.launcher.ModuleLauncher.java
private void launchModuleWithDependencies(String module, String[] args, String[] includes, String[] excludes) { try {// w w w .j av a 2s . com Resource[] libraries = this.moduleResolver.resolve(toCoordinates(module), toCoordinateArray(includes), excludes); List<Archive> archives = new ArrayList<>(); for (Resource library : libraries) { archives.add(new JarFileArchive(library.getFile())); } MultiArchiveLauncher jarLauncher = new MultiArchiveLauncher(archives); jarLauncher.launch(args); } catch (IOException e) { throw new RuntimeException("failed to launch module: " + module, e); } }