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

The following examples show how to use org.springframework.core.io.Resource#getFilename() . 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
Source File: ResourceResolvingStubDownloader.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
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 File: Utility.java    From mercury with 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
Source File: PropertiesLoaderUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 4
Source File: AbstractAutoDeploymentStrategy.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 5
Source File: FileSystemAttachmentService.java    From genie with Apache License 2.0 6 votes vote down vote up
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 6
Source File: TransformedResource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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 7
Source File: ScriptResource.java    From cuba with 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 8
Source File: SpringUtils.java    From onetwo with 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 9
Source File: MultiDataSourceInitializer.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
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 10
Source File: ResourceFinder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 11
Source File: MongoFactoryBean.java    From mongodb-orm with 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 12
Source File: BootstrapThemePopulator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 13
Source File: ResourceFinder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 14
Source File: FormHttpMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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 15
Source File: FormHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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 16
Source File: SpringCloudS3.java    From tutorials with 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 17
Source File: TransformedResource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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 18
Source File: ResourceFinder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 19
Source File: CssLinkResourceTransformer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@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
Source File: JsonProctorLoaderFactory.java    From proctor with Apache License 2.0 4 votes vote down vote up
private String generateExportVariableName(final Resource resource) {
    return EXPORT_NAME_PREFIX_FOR_SPECIFICATION + "-" + resource.getFilename();
}