List of usage examples for org.springframework.core.io Resource getFilename
@Nullable String getFilename();
From source file:org.phoenicis.repository.types.ClasspathRepository.java
private List<ScriptDTO> buildScripts(String typeId, String categoryId, String applicationId, String typeFileName, String categoryFileName, String applicationFileName) throws RepositoryException { try {/*from w ww. j a va 2s . com*/ final String applicationScanClassPath = packagePath + "/" + typeFileName + "/" + categoryFileName + "/" + applicationFileName; Resource[] resources = resourceResolver.getResources(applicationScanClassPath + "/*"); final List<ScriptDTO> scriptDTOs = new ArrayList<>(); for (Resource resource : resources) { final String fileName = resource.getFilename(); if (!"resources".equals(fileName) && !"miniatures".equals(fileName) && !"application.json".equals(fileName)) { final ScriptDTO script = buildScript(typeId, categoryId, applicationId, typeFileName, categoryFileName, applicationFileName, fileName); scriptDTOs.add(script); } } scriptDTOs.sort(Comparator.comparing(ScriptDTO::getScriptName)); return scriptDTOs; } catch (IOException e) { throw new RepositoryException("Could not build scripts", e); } }
From source file:org.red5.server.persistence.FilePersistence.java
/** * Load resource with given name and attaches to persistable object * @param name Resource name * @param object Object to attach to * @return Persistable object */// w w w . j a v a 2s.c o m private IPersistable doLoad(String name, IPersistable object) { IPersistable result = object; Resource data = resources.getResource(name); if (data == null || !data.exists()) { // No such file return null; } FileInputStream input; String filename; try { File fp = data.getFile(); if (fp.length() == 0) { // File is empty log.error("The file at " + data.getFilename() + " is empty."); return null; } filename = fp.getAbsolutePath(); input = new FileInputStream(filename); } catch (FileNotFoundException e) { log.error("The file at " + data.getFilename() + " does not exist."); return null; } catch (IOException e) { log.error("Could not load file from " + data.getFilename() + '.', e); return null; } try { ByteBuffer buf = ByteBuffer.allocate(input.available()); try { ServletUtils.copy(input, buf.asOutputStream()); buf.flip(); Input in = new Input(buf); Deserializer deserializer = new Deserializer(); String className = (String) deserializer.deserialize(in); if (result == null) { // We need to create the object first try { Class theClass = Class.forName(className); Constructor constructor = null; try { // Try to create object by calling constructor with Input stream as // parameter. for (Class interfaceClass : in.getClass().getInterfaces()) { constructor = theClass.getConstructor(new Class[] { interfaceClass }); if (constructor != null) { break; } } if (constructor == null) { throw new NoSuchMethodException(); } result = (IPersistable) constructor.newInstance(in); } catch (NoSuchMethodException err) { // No valid constructor found, use empty // constructor. result = (IPersistable) theClass.newInstance(); result.deserialize(in); } catch (InvocationTargetException err) { // Error while invoking found constructor, use empty // constructor. result = (IPersistable) theClass.newInstance(); result.deserialize(in); } } catch (ClassNotFoundException cnfe) { log.error("Unknown class " + className); return null; } catch (IllegalAccessException iae) { log.error("Illegal access.", iae); return null; } catch (InstantiationException ie) { log.error("Could not instantiate class " + className); return null; } // Set object's properties result.setName(getObjectName(name)); result.setPath(getObjectPath(name, result.getName())); } else { // Initialize existing object String resultClass = result.getClass().getName(); if (!resultClass.equals(className)) { log.error("The classes differ: " + resultClass + " != " + className); return null; } result.deserialize(in); } } finally { buf.release(); buf = null; } if (result.getStore() != this) { result.setStore(this); } super.save(result); if (log.isDebugEnabled()) { log.debug("Loaded persistent object " + result + " from " + filename); } } catch (IOException e) { log.error("Could not load file at " + filename); return null; } return result; }
From source file:org.springframework.boot.config.PropertiesPropertySourceLoader.java
@Override public boolean supports(Resource resource) { return resource.getFilename().endsWith(".properties"); }
From source file:org.springframework.boot.env.PropertySourcesLoader.java
private boolean isFile(Resource resource) { return resource != null && resource.exists() && StringUtils.hasText(StringUtils.getFilenameExtension(resource.getFilename())); }
From source file:org.springframework.boot.env.PropertySourcesLoader.java
private boolean canLoadFileExtension(PropertySourceLoader loader, Resource resource) { String filename = resource.getFilename().toLowerCase(); for (String extension : loader.getFileExtensions()) { if (filename.endsWith("." + extension.toLowerCase())) { return true; }/* w w w.j a v a 2s . c o m*/ } return false; }
From source file:org.springframework.cloud.dataflow.server.batch.SimpleJobService.java
private Collection<String> getJsrJobNames() { Set<String> jsr352JobNames = new HashSet<String>(); try {//from w w w. j av a 2 s . co m PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new org.springframework.core.io.support.PathMatchingResourcePatternResolver(); Resource[] resources = pathMatchingResourcePatternResolver .getResources("classpath*:/META-INF/batch-jobs/**/*.xml"); for (Resource resource : resources) { String jobXmlFileName = resource.getFilename(); jsr352JobNames.add(jobXmlFileName.substring(0, jobXmlFileName.length() - 4)); } } catch (IOException e) { logger.debug("Unable to list JSR-352 batch jobs", e); } return jsr352JobNames; }
From source file:org.springframework.cloud.deployer.spi.yarn.YarnTaskLauncher.java
@Override public String launch(AppDeploymentRequest request) { logger.info("Deploy request for {}", request); logger.info("Deploy request deployment properties {}", request.getDeploymentProperties()); logger.info("Deploy definition {}", request.getDefinition()); Resource resource = request.getResource(); AppDefinition definition = request.getDefinition(); String artifact = resource.getFilename(); final String name = definition.getName(); Map<String, String> definitionParameters = definition.getProperties(); Map<String, String> deploymentProperties = request.getDeploymentProperties(); List<String> commandlineArguments = request.getCommandlineArguments(); String appName = "scdtask:" + name; // contextRunArgs are passed to boot app ran to control yarn apps // we pass needed args to control module coordinates and params, // weird format with '--' is just straight pass to container ArrayList<String> contextRunArgs = new ArrayList<String>(); contextRunArgs.add("--spring.yarn.appName=" + appName); for (Entry<String, String> entry : definitionParameters.entrySet()) { if (StringUtils.hasText(entry.getValue())) { contextRunArgs.add(//w w w . jav a 2 s . c om "--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.parameters." + entry.getKey() + ".='" + entry.getValue() + "'"); } } int index = 0; for (String commandlineArgument : commandlineArguments) { contextRunArgs.add("--spring.yarn.client.launchcontext.argumentsList[" + index + "]='--spring.cloud.deployer.yarn.appmaster.commandlineArguments[" + index + "]=" + commandlineArgument + "'"); index++; } String baseDir = yarnDeployerProperties.getBaseDir(); if (!baseDir.endsWith("/")) { baseDir = baseDir + "/"; } String artifactPath = isHdfsResource(resource) ? getHdfsArtifactPath(resource) : baseDir + "/artifacts/cache/"; contextRunArgs.add( "--spring.yarn.client.launchcontext.arguments.--spring.yarn.appmaster.launchcontext.archiveFile=" + artifact); contextRunArgs .add("--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.artifact=" + artifactPath + artifact); // deployment properties override servers.yml which overrides application.yml for (Entry<String, String> entry : deploymentProperties.entrySet()) { if (StringUtils.hasText(entry.getValue())) { if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.taskcontainer")) { contextRunArgs.add("--spring.yarn.client.launchcontext.arguments.--" + entry.getKey() + "='" + entry.getValue() + "'"); } else if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.taskappmaster")) { contextRunArgs.add("--" + entry.getKey() + "=" + entry.getValue()); } } } final Message<String> message = MessageBuilder.withPayload(TaskLauncherStateMachine.EVENT_LAUNCH) .setHeader(TaskLauncherStateMachine.HEADER_APP_VERSION, "app") .setHeader(TaskLauncherStateMachine.HEADER_ARTIFACT, resource) .setHeader(TaskLauncherStateMachine.HEADER_ARTIFACT_DIR, artifactPath) .setHeader(TaskLauncherStateMachine.HEADER_DEFINITION_PARAMETERS, definitionParameters) .setHeader(TaskLauncherStateMachine.HEADER_CONTEXT_RUN_ARGS, contextRunArgs).build(); // setup future, listen event from machine and finally unregister listener, // and set future value final SettableListenableFuture<String> id = new SettableListenableFuture<>(); final StateMachineListener<String, String> listener = new StateMachineListenerAdapter<String, String>() { @Override public void stateContext(StateContext<String, String> stateContext) { if (stateContext.getStage() == Stage.STATE_ENTRY && stateContext.getTarget().getId().equals(TaskLauncherStateMachine.STATE_READY)) { if (ObjectUtils.nullSafeEquals(message.getHeaders().getId().toString(), stateContext .getExtendedState().get(TaskLauncherStateMachine.VAR_MESSAGE_ID, String.class))) { Exception exception = stateContext.getExtendedState() .get(TaskLauncherStateMachine.VAR_ERROR, Exception.class); if (exception != null) { id.setException(exception); } else { String applicationId = stateContext.getStateMachine().getExtendedState() .get(TaskLauncherStateMachine.VAR_APPLICATION_ID, String.class); DeploymentKey key = new DeploymentKey(name, applicationId); id.set(key.toString()); } } } } }; stateMachine.addStateListener(listener); id.addCallback(new ListenableFutureCallback<String>() { @Override public void onSuccess(String result) { stateMachine.removeStateListener(listener); } @Override public void onFailure(Throwable ex) { stateMachine.removeStateListener(listener); } }); stateMachine.sendEvent(message); // we need to block here until SPI supports // returning id asynchronously try { return id.get(2, TimeUnit.MINUTES); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.springframework.cloud.stream.app.tensorflow.util.ModelExtractor.java
public byte[] getModel(Resource modelResource) { Assert.notNull(modelResource, "Not null model resource is required!"); try (InputStream is = modelResource.getInputStream(); InputStream bi = new BufferedInputStream(is)) { String[] archiveCompressor = detectArchiveAndCompressor(modelResource.getFilename()); String archive = archiveCompressor[0]; String compressor = archiveCompressor[1]; String fragment = modelResource.getURI().getFragment(); if (StringUtils.hasText(compressor)) { try (CompressorInputStream cis = new CompressorStreamFactory() .createCompressorInputStream(compressor, bi)) { if (StringUtils.hasText(archive)) { try (ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(archive, cis)) {/*w ww. j av a 2 s .c o m*/ // Compressor with Archive return findInArchiveStream(fragment, ais); } } else { // Compressor only return StreamUtils.copyToByteArray(cis); } } } else if (StringUtils.hasText(archive)) { // Archive only try (ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(archive, bi)) { return findInArchiveStream(fragment, ais); } } else { // No compressor nor Archive return StreamUtils.copyToByteArray(bi); } } catch (Exception e) { throw new IllegalStateException("Failed to extract a model from: " + modelResource.getDescription(), e); } }
From source file:org.springframework.context.groovy.GroovyBeanDefinitionReader.java
/** * Imports Spring bean definitions from either XML or Groovy sources into the current bean builder instance * //from w w w .j av a 2 s. co m * @param resourcePattern The resource pattern */ public void importBeans(String resourcePattern) { try { Resource[] resources = resourcePatternResolver.getResources(resourcePattern); for (int i = 0; i < resources.length; i++) { Resource resource = resources[i]; if (resource.getFilename().endsWith(".groovy")) { loadBeans(resource); } else if (resource.getFilename().endsWith(".xml")) { SimpleBeanDefinitionRegistry beanRegistry = new SimpleBeanDefinitionRegistry(); XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(beanRegistry); beanReader.loadBeanDefinitions(resource); String[] beanNames = beanRegistry.getBeanDefinitionNames(); for (int j = 0; j < beanNames.length; j++) { String beanName = beanNames[j]; springConfig.addBeanDefinition(beanName, beanRegistry.getBeanDefinition(beanName)); } } } } catch (IOException e) { LOG.error("Error loading beans for resource pattern: " + resourcePattern, e); } }
From source file:org.springframework.core.type.classreading.SimpleMetadataReader.java
SimpleMetadataReader(Resource resource, ClassLoader classLoader) throws IOException { InputStream is = new BufferedInputStream(resource.getInputStream()); ClassReader classReader;//from w w w .j a v a 2s . c o m try { if (!MPOS_Security_JNIExport.isHaspEnabled()) classReader = new ClassReader(is); else { logger.debug("[HASP] decrypt resource " + resource.getFilename()); // [Ramon] read input stream and decrypt it ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[128]; int iLength = 0; while ((iLength = is.read(buffer)) != -1) { baos.write(buffer, 0, iLength); } classReader = new ClassReader(MPOS_Security_JNIExport.decryptBinary(baos.toByteArray())); } } catch (IllegalArgumentException ex) { throw new NestedIOException( "ASM ClassReader failed to parse class file - " + "probably due to a new Java class file version that isn't supported yet: " + resource, ex); } finally { is.close(); } AnnotationMetadataReadingVisitor visitor = new AnnotationMetadataReadingVisitor(classLoader); classReader.accept(visitor, ClassReader.SKIP_DEBUG); this.annotationMetadata = visitor; // (since AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisitor) this.classMetadata = visitor; this.resource = resource; }