List of usage examples for org.springframework.core.io Resource getFilename
@Nullable String getFilename();
From source file:org.springframework.data.hadoop.fs.DistributedCacheFactoryBean.java
@Override public void afterPropertiesSet() throws Exception { Assert.notNull(conf, "A Hadoop configuration is required"); Assert.notEmpty(entries, "No entries specified"); // fall back to system discovery if (fs == null) { fs = FileSystem.get(conf); }/* ww w.j a v a 2 s . c o m*/ ds = new DistributedCache(); if (createSymlink) { DistributedCache.createSymlink(conf); } HdfsResourceLoader loader = new HdfsResourceLoader(conf); boolean warnCpEntry = !":".equals(System.getProperty("path.separator")); try { for (CacheEntry entry : entries) { Resource[] resources = loader.getResources(entry.value); if (!ObjectUtils.isEmpty(resources)) { for (Resource resource : resources) { HdfsResource res = (HdfsResource) resource; URI uri = res.getURI(); String path = getPathWithFragment(uri); String defaultLink = resource.getFilename(); boolean isArchive = (defaultLink.endsWith(".tgz") || defaultLink.endsWith(".tar") || defaultLink.endsWith(".tar.gz") || defaultLink.endsWith(".zip")); switch (entry.type) { case CP: // Path does not handle fragments so use the URI instead Path p = new Path(URI.create(path)); if (FILE_SEPARATOR_WARNING && warnCpEntry) { LogFactory.getLog(DistributedCacheFactoryBean.class).warn( "System path separator is not ':' - this will likely cause invalid classpath entries within the DistributedCache. See the docs and HADOOP-9123 for more information."); // show the warning once per CL FILE_SEPARATOR_WARNING = false; } if (isArchive) { DistributedCache.addArchiveToClassPath(p, conf, fs); } else { DistributedCache.addFileToClassPath(p, conf, fs); } break; case LOCAL: if (isArchive) { if (VersionUtils.isHadoop2X()) { // TODO - Need to figure out how to add local archive } else { Method addLocalArchives = ReflectionUtils.findMethod(DistributedCache.class, "addLocalArchives", Configuration.class, String.class); addLocalArchives.invoke(null, conf, path); } } else { if (VersionUtils.isHadoop2X()) { // TODO - Need to figure out how to add local files } else { Method addLocalFiles = ReflectionUtils.findMethod(DistributedCache.class, "addLocalFiles", Configuration.class, String.class); addLocalFiles.invoke(null, conf, path); } } break; case CACHE: if (!path.contains("#")) { // use the path to avoid adding the host:port into the uri uri = URI.create(path + "#" + defaultLink); } if (isArchive) { DistributedCache.addCacheArchive(uri, conf); } else { DistributedCache.addCacheFile(uri, conf); } break; } } } } } finally { loader.close(); } }
From source file:org.springframework.http.converter.FormHttpMessageConverter.java
/** * Return the filename of the given multipart part. This value will be used for the * {@code Content-Disposition} header./*from w w w . jav a 2 s . co m*/ * <p>The default implementation returns {@link Resource#getFilename()} if the part is a * {@code Resource}, and {@code null} in other cases. Can be overridden in subclasses. * @param part the part to determine the file name for * @return the filename, or {@code null} if not known */ @Nullable protected String getFilename(Object part) { if (part instanceof Resource) { Resource resource = (Resource) part; String filename = resource.getFilename(); if (filename != null && this.multipartCharset != null) { filename = MimeDelegate.encode(filename, this.multipartCharset.name()); } return filename; } else { return null; } }
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 */// w ww . j a va2 s. c o 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; }
From source file:org.springframework.integration.expression.ReloadableResourceBundleExpressionSource.java
/** * Load the properties from the given resource. * @param resource the resource to load from * @param filename the original bundle filename (basename + Locale) * @return the populated Properties instance * @throws IOException if properties loading failed */// w w w . j a v a2s. co m private Properties loadProperties(Resource resource, String filename) throws IOException { InputStream is = resource.getInputStream(); Properties props = new Properties(); try { if (resource.getFilename().endsWith(XML_SUFFIX)) { if (logger.isDebugEnabled()) { logger.debug("Loading properties [" + resource.getFilename() + "]"); } this.propertiesPersister.loadFromXml(props, is); } else { String encoding = null; if (this.fileEncodings != null) { encoding = this.fileEncodings.getProperty(filename); } if (encoding == null) { encoding = this.defaultEncoding; } if (encoding != null) { if (logger.isDebugEnabled()) { logger.debug("Loading properties [" + resource.getFilename() + "] with encoding '" + encoding + "'"); } this.propertiesPersister.load(props, new InputStreamReader(is, encoding)); } else { if (logger.isDebugEnabled()) { logger.debug("Loading properties [" + resource.getFilename() + "]"); } this.propertiesPersister.load(props, is); } } return props; } finally { is.close(); } }
From source file:org.springframework.orm.jpa.persistenceunit.PersistenceUnitReader.java
/** * Determine the persistence unit root URL based on the given resource * (which points to the {@code persistence.xml} file we're reading). * @param resource the resource to check * @return the corresponding persistence unit root URL * @throws IOException if the checking failed *///from w w w . ja v a2 s .co m @Nullable static URL determinePersistenceUnitRootUrl(Resource resource) throws IOException { URL originalURL = resource.getURL(); // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec) if (ResourceUtils.isJarURL(originalURL)) { return ResourceUtils.extractJarFileURL(originalURL); } // Check META-INF folder String urlToString = originalURL.toExternalForm(); if (!urlToString.contains(META_INF)) { if (logger.isInfoEnabled()) { logger.info(resource.getFilename() + " should be located inside META-INF directory; cannot determine persistence unit root URL for " + resource); } return null; } if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) { if (logger.isInfoEnabled()) { logger.info(resource.getFilename() + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for " + resource); } return null; } String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF)); if (persistenceUnitRoot.endsWith("/")) { persistenceUnitRoot = persistenceUnitRoot.substring(0, persistenceUnitRoot.length() - 1); } return new URL(persistenceUnitRoot); }
From source file:org.springframework.social.twitter.api.impl.ton.TonTemplateTest.java
@Test public void uploadChunk() throws IOException { mockServer.expect(requestTo("https://ton.twitter.com/1.1/ton/bucket/ta_partner")).andExpect(method(POST)) .andRespond(withCreatedEntity(URI.create(RESPONSE_URI))); Resource resource = dataResource("hashed_twitter.txt"); InputStream is = resource.getInputStream(); String contentType = URLConnection.guessContentTypeFromName(resource.getFilename()); byte[] data = bufferObj(is); ZonedDateTime expiry = ZonedDateTime.now().plusDays(7); URI uri = twitter.tonOperations().uploadSingleChunk(BUCKET_NAME, data, contentType, expiry); assertEquals(uri.toString(), RESPONSE_URI); }
From source file:org.springframework.web.reactive.resource.AppCacheManifestTransformer.java
private Mono<? extends Resource> transform(String content, Resource resource, ResourceTransformerChain chain, ServerWebExchange exchange) {/*w ww .j av a 2 s . com*/ if (!content.startsWith(MANIFEST_HEADER)) { if (logger.isTraceEnabled()) { logger.trace("Manifest should start with 'CACHE MANIFEST', skip: " + resource); } return Mono.just(resource); } if (logger.isTraceEnabled()) { logger.trace("Transforming resource: " + resource); } return Flux.generate(new LineInfoGenerator(content)) .concatMap(info -> processLine(info, exchange, resource, chain)) .reduce(new ByteArrayOutputStream(), (out, line) -> { writeToByteArrayOutputStream(out, line + "\n"); return out; }).map(out -> { String hash = DigestUtils.md5DigestAsHex(out.toByteArray()); writeToByteArrayOutputStream(out, "\n" + "# Hash: " + hash); if (logger.isTraceEnabled()) { logger.trace("AppCache file: [" + resource.getFilename() + "] hash: [" + hash + "]"); } return new TransformedResource(resource, out.toByteArray()); }); }
From source file:org.springframework.web.servlet.resource.AppCacheManifestTransfomer.java
@Override public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException { resource = transformerChain.transform(request, resource); String filename = resource.getFilename(); if (!this.fileExtension.equals(StringUtils.getFilenameExtension(filename))) { return resource; }/*from w w w . j a va 2s . c o m*/ byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); String content = new String(bytes, DEFAULT_CHARSET); if (!content.startsWith(MANIFEST_HEADER)) { if (logger.isTraceEnabled()) { logger.trace("AppCache manifest does not start with 'CACHE MANIFEST', skipping: " + resource); } return resource; } if (logger.isTraceEnabled()) { logger.trace("Transforming resource: " + resource); } StringWriter contentWriter = new StringWriter(); HashBuilder hashBuilder = new HashBuilder(content.length()); Scanner scanner = new Scanner(content); SectionTransformer currentTransformer = this.sectionTransformers.get(MANIFEST_HEADER); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (this.sectionTransformers.containsKey(line.trim())) { currentTransformer = this.sectionTransformers.get(line.trim()); contentWriter.write(line + "\n"); hashBuilder.appendString(line); } else { contentWriter .write(currentTransformer.transform(line, hashBuilder, resource, transformerChain) + "\n"); } } String hash = hashBuilder.build(); contentWriter.write("\n" + "# Hash: " + hash); if (logger.isTraceEnabled()) { logger.trace("AppCache file: [" + resource.getFilename() + "] Hash: [" + hash + "]"); } return new TransformedResource(resource, contentWriter.toString().getBytes(DEFAULT_CHARSET)); }
From source file:org.springframework.web.servlet.resource.AppCacheManifestTransformer.java
@Override public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain chain) throws IOException { resource = chain.transform(request, resource); if (!this.fileExtension.equals(StringUtils.getFilenameExtension(resource.getFilename()))) { return resource; }/*from www. j av a2 s. c o m*/ byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); String content = new String(bytes, DEFAULT_CHARSET); if (!content.startsWith(MANIFEST_HEADER)) { if (logger.isTraceEnabled()) { logger.trace("Manifest should start with 'CACHE MANIFEST', skip: " + resource); } return resource; } if (logger.isTraceEnabled()) { logger.trace("Transforming resource: " + resource); } Scanner scanner = new Scanner(content); LineInfo previous = null; LineAggregator aggregator = new LineAggregator(resource, content); while (scanner.hasNext()) { String line = scanner.nextLine(); LineInfo current = new LineInfo(line, previous); LineOutput lineOutput = processLine(current, request, resource, chain); aggregator.add(lineOutput); previous = current; } return aggregator.createResource(); }
From source file:org.springframework.web.servlet.resource.CssLinkResourceTransformer.java
@Override public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException { resource = transformerChain.transform(request, resource); String filename = resource.getFilename(); if (!"css".equals(StringUtils.getFilenameExtension(filename)) || resource instanceof GzipResourceResolver.GzippedResource) { return resource; }/*w ww. j a v a 2 s . co m*/ if (logger.isTraceEnabled()) { logger.trace("Transforming resource: " + resource); } byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); String content = new String(bytes, DEFAULT_CHARSET); SortedSet<ContentChunkInfo> links = new TreeSet<>(); for (LinkParser parser : this.linkParsers) { parser.parse(content, links); } if (links.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("No links found."); } return resource; } int index = 0; StringWriter writer = new StringWriter(); for (ContentChunkInfo linkContentChunkInfo : links) { writer.write(content.substring(index, linkContentChunkInfo.getStart())); String link = content.substring(linkContentChunkInfo.getStart(), linkContentChunkInfo.getEnd()); String newLink = null; if (!hasScheme(link)) { String absolutePath = toAbsolutePath(link, request); newLink = resolveUrlPath(absolutePath, request, resource, transformerChain); } if (logger.isTraceEnabled()) { if (newLink != null && !newLink.equals(link)) { logger.trace("Link modified: " + newLink + " (original: " + link + ")"); } else { logger.trace("Link not modified: " + link); } } writer.write(newLink != null ? newLink : link); index = linkContentChunkInfo.getEnd(); } writer.write(content.substring(index)); return new TransformedResource(resource, writer.toString().getBytes(DEFAULT_CHARSET)); }