Java Code Examples for org.springframework.core.io.Resource#getFilename()

The following examples show how to use org.springframework.core.io.Resource#getFilename() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void copyTheFoundFiles(File tmp, Resource resource, String relativePath)
		throws IOException {
	// the relative path is OS agnostic and contains / only
	int lastIndexOf = relativePath.lastIndexOf("/");
	String relativePathWithoutFile = lastIndexOf > -1
			? relativePath.substring(0, lastIndexOf) : relativePath;
	if (log.isDebugEnabled()) {
		log.debug("Relative path without file name is [" + relativePathWithoutFile
				+ "]");
	}
	Path directory = Files
			.createDirectories(new File(tmp, relativePathWithoutFile).toPath());
	File newFile = new File(directory.toFile(), resource.getFilename());
	if (!newFile.exists() && !isDirectory(resource)) {
		try (InputStream stream = resource.getInputStream()) {
			Files.copy(stream, newFile.toPath());
			TemporaryFileStorage.add(newFile);
		}
	}
	if (log.isDebugEnabled()) {
		log.debug("Stored file [" + newFile + "]");
	}
}
 
Example 2
Source Project: mercury   File: Utility.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> getJarList(String path) {
    List<String> list = new ArrayList<>();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        Resource[] res = resolver.getResources(path);
        for (Resource r : res) {
            String name = r.getFilename();
            if (name != null) {
                list.add(name.endsWith(JAR) ? name.substring(0, name.length() - JAR.length()) : name);
            }
        }
    } catch (IOException e) {
        // ok to ignore
    }
    return list;
}
 
Example 3
/**
 * Determines the name to be used for the provided resource.
 * 
 * @param resource
 *          the resource to get the name for
 * @return the name of the resource
 */
protected String determineResourceName(final Resource resource) {
  String resourceName = null;

  if (resource instanceof ContextResource) {
    resourceName = ((ContextResource) resource).getPathWithinContext();

  } else if (resource instanceof ByteArrayResource) {
    resourceName = resource.getDescription();

  } else {
    try {
      resourceName = resource.getFile().getAbsolutePath();
    } catch (IOException e) {
      resourceName = resource.getFilename();
    }
  }
  return resourceName;
}
 
Example 4
private Set<URI> writeAttachments(final String id, final Set<Resource> attachments) throws IOException {
    if (attachments.isEmpty()) {
        return ImmutableSet.of();
    }
    final Path requestDir = Files.createDirectories(this.attachmentDirectory.resolve(id));
    final ImmutableSet.Builder<URI> uris = ImmutableSet.builder();

    for (final Resource attachment : attachments) {
        final String rawFilename = attachment.getFilename() == null
            ? UUID.randomUUID().toString()
            : attachment.getFilename();
        // Sanitize the filename
        final Path fileName = Paths.get(rawFilename).getFileName();
        final Path file = requestDir.resolve(fileName);
        try (InputStream contents = attachment.getInputStream()) {
            final long byteCount = Files.copy(contents, file);
            log.debug("Wrote {} bytes for attachment {} to {}", byteCount, fileName, file);
        }
        uris.add(file.toUri());
    }
    return uris.build();
}
 
Example 5
/**
 * Fill the given properties from the given resource (in ISO-8859-1 encoding).
 * @param props the Properties instance to fill
 * @param resource the resource to load from
 * @throws IOException if loading failed
 */
public static void fillProperties(Properties props, Resource resource) throws IOException {
	InputStream is = resource.getInputStream();
	try {
		String filename = resource.getFilename();
		if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
			props.loadFromXML(is);
		}
		else {
			props.load(is);
		}
	}
	finally {
		is.close();
	}
}
 
Example 6
public static InputStream getInputStream(String path) {
   Resource r = getResource(path);
   InputStream is = null;
   try {
      is = r.getInputStream();
   } catch (IOException e) {
      throw new RuntimeException("Failed to get inputstream for: " + r.getFilename(), e);
   }
   return is;
}
 
Example 7
public TransformedResource(Resource original, byte[] transformedContent) {
	super(transformedContent);
	this.filename = original.getFilename();
	try {
		this.lastModified = original.lastModified();
	}
	catch (IOException ex) {
		// should never happen
		throw new IllegalArgumentException(ex);
	}
}
 
Example 8
Source Project: tutorials   File: SpringCloudS3.java    License: MIT License 5 votes vote down vote up
public void downloadS3Object(String s3Url) throws IOException {
    Resource resource = resourceLoader.getResource(s3Url);
    File downloadedS3Object = new File(resource.getFilename());
    try (InputStream inputStream = resource.getInputStream()) {
        Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}
 
Example 9
/**
 * Return the filename of the given multipart part. This value will be used for the
 * {@code Content-Disposition} header.
 * <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;
	}
}
 
Example 10
/**
 * Return the filename of the given multipart part. This value will be used for the
 * {@code Content-Disposition} header.
 * <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;
	}
}
 
Example 11
public TransformedResource(Resource original, byte[] transformedContent) {
	super(transformedContent);
	this.filename = original.getFilename();
	try {
		this.lastModified = original.lastModified();
	}
	catch (IOException ex) {
		// should never happen
		throw new IllegalArgumentException(ex);
	}
}
 
Example 12
public static InputStream[] getInputStreams(List<String> paths) {
   List<Resource> rs = makeResources(paths);
   InputStream[] streams = new InputStream[rs.size()];
   for (int i = 0; i < rs.size(); i++) {
      Resource r = rs.get(i);
      try {
         streams[i] = r.getInputStream();
      } catch (IOException e) {
         throw new RuntimeException("Failed to get inputstream for: " + r.getFilename(), e);
      }
   }
   return streams;
}
 
Example 13
private void addBootstrap3And4Style(
    String bootstrap3FileName, InputStream bootstrap3Data, Resource bootstrap4resource) {
  try (InputStream bootstrap4Data = bootstrap4resource.getInputStream()) {
    String bootstrap4FileName = bootstrap4resource.getFilename();
    LOG.debug("Adding matching bootstrap 4 theme with name {}", bootstrap4FileName);
    styleService.addStyle(
        bootstrap3FileName,
        bootstrap3FileName,
        bootstrap3Data,
        bootstrap4FileName,
        bootstrap4Data);
  } catch (Exception e) {
    LOG.error("error adding new bootstrap 4 theme", e);
  }
}
 
Example 14
Source Project: mongodb-orm   File: MongoFactoryBean.java    License: Apache License 2.0 5 votes vote down vote up
public void init() throws Exception {
  MqlMapConfigParser configParser = new MqlMapConfigParser();
  for (Resource configLocation : configLocations) {
    InputStream is = configLocation.getInputStream();
    try {
      configParser.parse(is);
      logger.info("Mql configuration parse resource file. File name is " + configLocation.getFilename());
    } catch (RuntimeException ex) {
      throw new NestedIOException("Failed to parse config configuration. File name is " + configLocation.getFilename(), ex.getCause());
    }
  }
  configParser.validateMapping();
  this.configParser = configParser;
  logger.info("Mongodb orm framework has ready.");
}
 
Example 15
public static InputStream[] getInputStreams(List<String> paths) {
   List<Resource> rs = makeResources(paths);
   InputStream[] streams = new InputStream[rs.size()];
   for (int i = 0; i < rs.size(); i++) {
      Resource r = rs.get(i);
      try {
         streams[i] = r.getInputStream();
      } catch (IOException e) {
         throw new RuntimeException("Failed to get inputstream for: " + r.getFilename(), e);
      }
   }
   return streams;
}
 
Example 16
List<Resource> getResources(String propertyName, List<String> locations, boolean validate) {
    List<Resource> resources = new ArrayList<Resource>();
    for (String location : locations) {
        for (Resource resource : doGetResources(location)) {
            if (resource.exists()) {
                resources.add(resource);
            } else if (validate) {
                throw new TeiidRuntimeException(resource.getFilename() + " does not exist!");
            }
        }
    }
    return resources;
}
 
Example 17
Source Project: onetwo   File: SpringUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static InputStream getInputStream(Resource resource){
	try {
		return resource.getInputStream();
	} catch (IOException e) {
		throw new BaseException("get InputStream error: " + resource.getFilename());
	}
}
 
Example 18
Source Project: cuba   File: ScriptResource.java    License: Apache License 2.0 5 votes vote down vote up
public ScriptResource(Resource resource) {
    try {
        this.resource = resource;
        this.name = resource.getFilename();
        this.path = URLEncodeUtils.decodeUtf8(resource.getURL().getPath());
        this.dir = StringUtils.substringBeforeLast(this.path, "/");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 19
@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))) {
		return resource;
	}

	if (logger.isTraceEnabled()) {
		logger.trace("Transforming resource: " + resource);
	}

	byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
	String content = new String(bytes, DEFAULT_CHARSET);

	Set<CssLinkInfo> infos = new HashSet<CssLinkInfo>(8);
	for (CssLinkParser parser : this.linkParsers) {
		parser.parseLink(content, infos);
	}

	if (infos.isEmpty()) {
		if (logger.isTraceEnabled()) {
			logger.trace("No links found.");
		}
		return resource;
	}

	List<CssLinkInfo> sortedInfos = new ArrayList<CssLinkInfo>(infos);
	Collections.sort(sortedInfos);

	int index = 0;
	StringWriter writer = new StringWriter();
	for (CssLinkInfo info : sortedInfos) {
		writer.write(content.substring(index, info.getStart()));
		String link = content.substring(info.getStart(), info.getEnd());
		String newLink = null;
		if (!hasScheme(link)) {
			newLink = resolveUrlPath(link, request, resource, transformerChain);
		}
		if (logger.isTraceEnabled()) {
			if (newLink != null && !link.equals(newLink)) {
				logger.trace("Link modified: " + newLink + " (original: " + link + ")");
			}
			else {
				logger.trace("Link not modified: " + link);
			}
		}
		writer.write(newLink != null ? newLink : link);
		index = info.getEnd();
	}
	writer.write(content.substring(index));

	return new TransformedResource(resource, writer.toString().getBytes(DEFAULT_CHARSET));
}
 
Example 20
private String generateExportVariableName(final Resource resource) {
    return EXPORT_NAME_PREFIX_FOR_SPECIFICATION + "-" + resource.getFilename();
}