List of usage examples for org.springframework.core.io Resource getFilename
@Nullable String getFilename();
From source file:org.shept.util.JarUtils.java
/** * Copy resources from a classPath, typically within a jar file * to a specified destination, typically a resource directory in * the projects webApp directory (images, sounds, e.t.c. ) * //from ww w .j av a 2 s . c om * Copies resources only if the destination file does not exist and * the specified resource is available. * * @param resources Array of String resources (filenames) to be copied * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar) * @param webAppDestPath Full path String to the fileSystem destination directory * @throws IOException when copying on copy error */ public static void copyResources(String[] resources, ClassPathResource cpr, String webAppDestPath) throws IOException { String dstPath = webAppDestPath; // + "/" + jarPathInternal(cpr.getURL()); File dir = new File(dstPath); dir.mkdirs(); for (int i = 0; i < resources.length; i++) { File dstFile = new File(dstPath, resources[i]); // (StringUtils.applyRelativePath(dstPath, images[i])); Resource fileRes = cpr.createRelative(resources[i]); if (!dstFile.exists() && fileRes.exists()) { FileOutputStream fos = new FileOutputStream(dstFile); FileCopyUtils.copy(fileRes.getInputStream(), fos); logger.info("Successfully copied file " + fileRes.getFilename() + " from " + cpr.getPath() + " to " + dstFile.getPath()); } } }
From source file:me.springframework.di.spring.AliasTest.java
private static Configuration readConfiguration(Resource resource) { JavaDocBuilder builder = new JavaDocBuilder(); builder.addSourceTree(Paths.getFile("src/test/java")); Augmentation[] augmentations = { new QDoxAugmentation(builder), new AutowiringAugmentation(builder) }; SpringConfigurationLoader loader = new SpringConfigurationLoader(augmentations); ConfigurableApplicationContext ctxt = new ClassPathXmlApplicationContext(resource.getFilename()); Configuration configuration = loader.load(ctxt.getBeanFactory()); return configuration; }
From source file:org.jahia.modules.external.test.db.WriteableMappedDatabaseProvider.java
private static void extract(JahiaTemplatesPackage p, org.springframework.core.io.Resource r, File f) throws Exception { if ((r instanceof BundleResource && r.contentLength() == 0) || (!(r instanceof BundleResource) && r.getFile().isDirectory())) { f.mkdirs();/*from www . jav a2s . c o m*/ String path = r.getURI().getPath(); for (org.springframework.core.io.Resource resource : p .getResources(path.substring(path.indexOf("/toursdb")))) { extract(p, resource, new File(f, resource.getFilename())); } } else { FileOutputStream output = null; try { output = new FileOutputStream(f); IOUtils.copy(r.getInputStream(), output); } finally { IOUtils.closeQuietly(output); } } }
From source file:com.griddynamics.jagger.JaggerLauncher.java
private static List<String> discoverResources(URL directory, String[] includePatterns, String[] excludePatterns) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( new FileSystemResourceLoader()); List<String> resourceNames = new ArrayList<String>(); PathMatcher matcher = new AntPathMatcher(); try {// w w w . j a v a2s . co m for (String pattern : includePatterns) { Resource[] includeResources = resolver.getResources(directory.toString() + pattern); for (Resource resource : includeResources) { boolean isValid = true; for (String excludePattern : excludePatterns) { if (matcher.match(excludePattern, resource.getFilename())) { isValid = false; break; } } if (isValid) { resourceNames.add(resource.getURI().toString()); } } } } catch (IOException e) { throw new TechnicalException(e); } return resourceNames; }
From source file:nl.flotsam.hamcrest.schema.relaxng.RelaxNGMatchers.java
/** * Creates a RelaxNG matcher based on a {@link Resource} object pointing to a RelaxNG schema. (XML Syntax) *///from w ww.j a v a2 s.co m public static TypeSafeDiagnosingMatcher<Object> isValidatedBy(Resource resource) { VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl(); InputStream in = null; try { URI uri = resource.getURI(); in = resource.getInputStream(); if (uri == null) { return isValidatedBy(factory.compileSchema(in), resource.toString()); } else { return isValidatedBy(factory.compileSchema(in, resource.getURI().toASCIIString()), resource.getFilename()); } } catch (Exception e) { throw new IllegalStateException("Failed to construct matcher", e); } finally { IOUtils.closeQuietly(in); } }
From source file:com.glaf.core.entity.mybatis.MyBatisSessionFactory.java
protected static void reloadSessionFactory() { long start = System.currentTimeMillis(); Set<String> mappers = new HashSet<String>(); Configuration configuration = new Configuration(); String path = SystemProperties.getConfigRootPath() + "/conf/mapper"; try {/*from ww w. ja v a 2 s. com*/ Map<String, byte[]> dataMap = getLibMappers(); for (int i = 0; i < dataMap.size(); i++) { Set<Entry<String, byte[]>> entrySet = dataMap.entrySet(); for (Entry<String, byte[]> entry : entrySet) { String key = entry.getKey(); if (key.indexOf("/") != -1) { key = key.substring(key.lastIndexOf("/"), key.length()); } byte[] bytes = entry.getValue(); String filename = path + "/" + key; try { FileUtils.save(filename, bytes); } catch (Exception ex) { ex.printStackTrace(); } } } List<String> list = getClassPathMappers(); for (int i = 0; i < list.size(); i++) { Resource mapperLocation = new FileSystemResource(list.get(i)); try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); mappers.add(mapperLocation.getFilename()); } catch (Exception ex) { ex.printStackTrace(); throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", ex); } finally { ErrorContext.instance().reset(); } } File dir = new File(path); if (dir.exists() && dir.isDirectory()) { File contents[] = dir.listFiles(); if (contents != null) { for (int i = 0; i < contents.length; i++) { if (contents[i].isFile() && contents[i].getName().endsWith("Mapper.xml")) { if (mappers.contains(contents[i].getName())) { continue; } Resource mapperLocation = new FileSystemResource(contents[i]); try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder( mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception ex) { ex.printStackTrace(); throw new NestedIOException( "Failed to parse mapping resource: '" + mapperLocation + "'", ex); } finally { ErrorContext.instance().reset(); } } } } } sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); } catch (Exception ex) { ex.printStackTrace(); } long time = System.currentTimeMillis() - start; System.out.println("SessionFactory" + (time)); }
From source file:org.mitre.jdbc.datasource.H2DataSourceFactory.java
protected static void executeScripts(Connection connection, List<Resource> resources) { for (Resource script : resources) { try {/*w w w .j a v a 2s .co m*/ String sql = new SqlFileParser(script).getSQL(); logger.debug("Executing sql:\n" + sql); executeSql(sql, connection); logger.debug("Successfully executed statement"); } catch (IOException e) { throw new RuntimeException("File IO Exception while loading " + script.getFilename(), e); } catch (SQLException e) { throw new RuntimeException("SQL exception occurred loading data from " + script.getFilename(), e); } } }
From source file:fi.solita.phantomrunner.util.FileUtils.java
/** * Extracts the given resource to user's temporary directory (by creating a unique directory underneath * it). Will delete that file and created directories on system exit if deleteOnExit is true. * /*from w ww . ja v a2 s . com*/ * @param resource Resource to be extracted * @param subPath Slash (character '/') separated path of the sub-directories which should be created * @param deleteOnExit If the resource and created sub-directories should be deleted * * @return File handle to the created file in the temporary directory */ public static File extractResourceToTempDirectory(Resource resource, String subPath, boolean deleteOnExit) throws IOException { final File tempDir = Files.createTempDir(); if (deleteOnExit) tempDir.deleteOnExit(); File lastDir = tempDir; for (String subDir : subPath.split("/")) { // if the subPath starts or ends with '/' we'll get empty strings too if (StringUtils.hasLength(subDir)) { lastDir = new File(lastDir, subDir); lastDir.mkdir(); if (deleteOnExit) lastDir.deleteOnExit(); } } final File resFile = new File(lastDir, resource.getFilename()); resFile.createNewFile(); if (deleteOnExit) resFile.deleteOnExit(); IOUtil.copy(resource.getInputStream(), new FileWriter(resFile), "UTF-8"); return resFile; }
From source file:org.codehaus.groovy.grails.plugins.springsecurity.AuthorizeTools.java
@SuppressWarnings("unchecked") private static void loadExternalConfigs(final List<ConfigObject> configs, final ConfigObject config) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); List<String> locations = (List<String>) ConfigurationHolder.getFlatConfig() .get("springsecurity.config.locations"); if (locations != null) { for (String location : locations) { if (StringUtils.hasLength(location)) { try { Resource resource = resolver.getResource(location); InputStream stream = null; try { stream = resource.getInputStream(); ConfigSlurper configSlurper = new ConfigSlurper(GrailsUtil.getEnvironment()); configSlurper.setBinding(config); if (resource.getFilename().endsWith(".groovy")) { configs.add(configSlurper.parse(IOUtils.toString(stream))); } else if (resource.getFilename().endsWith(".properties")) { Properties props = new Properties(); props.load(stream); configs.add(configSlurper.parse(props)); }/*from ww w . j a v a 2s.co m*/ } finally { if (stream != null) { stream.close(); } } } catch (Exception e) { LOG.warn("Unable to load specified config location $location : ${e.message}"); LOG.debug("Unable to load specified config location $location : ${e.message}", e); } } } } }
From source file:de.ingrid.iplug.ckan.utils.ScriptEngine.java
/** * Execute the given scripts with the given parameters * @param scripts The script files/*from w w w . j a va2 s .c o m*/ * @param parameters The parameters * @param compile Boolean indicating whether to compile the script or not * @return Map with the absolute paths of the scripts as keys and the execution results as values * If an execution returns null, the result will not be added * @throws Exception */ public static Map<String, Object> execute(Resource[] scripts, Map<String, Object> parameters, boolean compile) throws Exception { Map<Integer, Bindings> bindings = new Hashtable<Integer, Bindings>(); Map<String, Object> results = new Hashtable<String, Object>(); for (Resource script : scripts) { // get the engine for the script javax.script.ScriptEngine engine = getEngine(script); // initialize/get the bindings if (!bindings.containsKey(engine.hashCode())) { Bindings newBindings = engine.createBindings(); newBindings.putAll(parameters); bindings.put(engine.hashCode(), newBindings); } Bindings curBindings = bindings.get(engine.hashCode()); // execute the script CompiledScript compiledScript = null; Object result = null; if (compile && (compiledScript = getCompiledScript(script)) != null) { result = compiledScript.eval(curBindings); } else { result = engine.eval(new InputStreamReader(script.getInputStream()), curBindings); } if (result != null) { results.put(script.getFilename(), result); } } return results; }