本文整理匯總了Java中org.springframework.core.io.Resource類的典型用法代碼示例。如果您正苦於以下問題:Java Resource類的具體用法?Java Resource怎麽用?Java Resource使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Resource類屬於org.springframework.core.io包,在下文中一共展示了Resource類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: renderInternal
import org.springframework.core.io.Resource; //導入依賴的package包/類
@Override
protected Mono<Void> renderInternal(Map<String, Object> model, MediaType contentType,
ServerWebExchange exchange) {
Resource resource = resolveResource();
if (resource == null) {
return Mono.error(new IllegalStateException(
"Could not find Mustache template with URL [" + getUrl() + "]"));
}
DataBuffer dataBuffer = exchange.getResponse().bufferFactory().allocateBuffer();
try (Reader reader = getReader(resource)) {
Template template = this.compiler.compile(reader);
Charset charset = getCharset(contentType).orElse(getDefaultCharset());
try (Writer writer = new OutputStreamWriter(dataBuffer.asOutputStream(),
charset)) {
template.execute(model, writer);
writer.flush();
}
}
catch (Exception ex) {
DataBufferUtils.release(dataBuffer);
return Mono.error(ex);
}
return exchange.getResponse().writeWith(Flux.just(dataBuffer));
}
示例2: computeFilename
import org.springframework.core.io.Resource; //導入依賴的package包/類
String computeFilename(Resource resource) throws IOException {
URI uri = resource.getURI();
StringBuilder stringBuilder = new StringBuilder();
String scheme = uri.getScheme();
if (scheme.equals("file")) {
stringBuilder.append("file");
if (uri.getPath() != null) {
stringBuilder.append(uri.getPath().replaceAll("/", "_"));
}
else {
String relativeFilename = uri.getSchemeSpecificPart().replaceAll("^./", "/dot/");
stringBuilder.append(relativeFilename.replaceAll("/", "_"));
}
}
else if (scheme.equals("http") || scheme.equals("https")) {
stringBuilder.append(uri.getHost()).append(uri.getPath().replaceAll("/", "_"));
}
else {
logger.warn("Package repository with scheme " + scheme
+ " is not supported. Skipping processing this repository.");
}
return stringBuilder.toString();
}
示例3: setUp
import org.springframework.core.io.Resource; //導入依賴的package包/類
@Before
public void setUp() {
applicationContext = new XmlWebApplicationContext();
applicationContext.setConfigLocations(
"file:src/main/webapp/WEB-INF/cas-servlet.xml",
"file:src/main/webapp/WEB-INF/deployerConfigContext.xml",
"file:src/main/webapp/WEB-INF/spring-configuration/*.xml");
applicationContext.setServletContext(new MockServletContext(new ResourceLoader() {
@Override
public Resource getResource(final String location) {
return new FileSystemResource("src/main/webapp" + location);
}
@Override
public ClassLoader getClassLoader() {
return getClassLoader();
}
}));
applicationContext.refresh();
}
示例4: loadContent
import org.springframework.core.io.Resource; //導入依賴的package包/類
private Map<String, String> loadContent() throws IOException
{
ClassPathStoreResourceResolver resourceResolver = new ClassPathStoreResourceResolver(applicationContext);
Resource[] contentResources = resourceResolver.getResources("classpath*:" + configPath + packageName + "/*.*");
Map<String, String> content = new HashMap<String, String>();
for (Resource contentResource : contentResources)
{
String fileName = contentResource.getFilename();
// ignore hidden directories / files
if (fileName.startsWith("."))
{
continue;
}
String key = packageName + "/" + fileName;
String value = convert(contentResource.getInputStream());
content.put(key, value);
}
return content;
}
示例5: PublicKeyspacePersistenceSettings
import org.springframework.core.io.Resource; //導入依賴的package包/類
/**
* Constructs Ignite cache key/value persistence settings.
*
* @param settingsRsrc resource containing xml with persistence settings for Ignite cache key/value
*/
public PublicKeyspacePersistenceSettings(Resource settingsRsrc) {
InputStream in;
try {
in = settingsRsrc.getInputStream();
}
catch (IOException e) {
throw new IgniteException("Failed to get input stream for Cassandra persistence settings resource: " +
settingsRsrc, e);
}
try {
init(loadSettings(in));
}
finally {
U.closeQuiet(in);
}
}
示例6: afterPropertiesSet
import org.springframework.core.io.Resource; //導入依賴的package包/類
/**
* Merges the {@code Properties} configured in the {@code mappings} and
* {@code mappingLocations} into the final {@code Properties} instance
* used for {@code ObjectName} resolution.
* @throws IOException
*/
@Override
public void afterPropertiesSet() throws IOException {
this.mergedMappings = new Properties();
CollectionUtils.mergePropertiesIntoMap(this.mappings, this.mergedMappings);
if (this.mappingLocations != null) {
for (int i = 0; i < this.mappingLocations.length; i++) {
Resource location = this.mappingLocations[i];
if (logger.isInfoEnabled()) {
logger.info("Loading JMX object name mappings file from " + location);
}
PropertiesLoaderUtils.fillProperties(this.mergedMappings, location);
}
}
}
示例7: convert
import org.springframework.core.io.Resource; //導入依賴的package包/類
/**
* Converts the 2-dimensional byte array of file data, which includes the name of the file as
* bytes followed by the byte content of the file, for all files being transmitted by Gfsh to the
* GemFire Manager.
* <p/>
*
* @param fileData a 2 dimensional byte array of files names and file content.
* @return an array of Spring Resource objects encapsulating the details (name and content) of
* each file being transmitted by Gfsh to the GemFire Manager.
* @see org.springframework.core.io.ByteArrayResource
* @see org.springframework.core.io.Resource
* @see org.apache.geode.management.internal.cli.CliUtil#bytesToData(byte[][])
* @see org.apache.geode.management.internal.cli.CliUtil#bytesToNames(byte[][])
*/
public static Resource[] convert(final byte[][] fileData) {
if (fileData != null) {
final String[] fileNames = CliUtil.bytesToNames(fileData);
final byte[][] fileContent = CliUtil.bytesToData(fileData);
final List<Resource> resources = new ArrayList<Resource>(fileNames.length);
for (int index = 0; index < fileNames.length; index++) {
final String filename = fileNames[index];
resources.add(new ByteArrayResource(fileContent[index],
String.format("Contents of JAR file (%1$s).", filename)) {
@Override
public String getFilename() {
return filename;
}
});
}
return resources.toArray(new Resource[resources.size()]);
}
return new Resource[0];
}
示例8: loadReport
import org.springframework.core.io.Resource; //導入依賴的package包/類
@Override
public InputStream loadReport(String file) {
Resource resource=applicationContext.getResource(file);
try {
return resource.getInputStream();
} catch (IOException e) {
String newFileName=null;
if(file.startsWith("classpath:")){
newFileName="classpath*:"+file.substring(10,file.length());
}else if(file.startsWith("classpath*:")){
newFileName="classpath:"+file.substring(11,file.length());
}
if(newFileName!=null){
try{
return applicationContext.getResource(file).getInputStream();
}catch(IOException ex){
throw new ReportException(e);
}
}
throw new ReportException(e);
}
}
示例9: createSpringContext
import org.springframework.core.io.Resource; //導入依賴的package包/類
/**
* Creates a Spring context.
*/
protected void createSpringContext() {
List<Resource> resources = resolveSpringConfigurationResources();
if (resources.isEmpty()) {
return;
}
logger.debug("Loading Spring configuration from {}", resources);
context = new GenericGroovyApplicationContext();
StandalonePlugin standalonePlugin = getStandalonePlugin();
context.getBeanFactory().registerSingleton(
standalonePlugin != null ? standalonePlugin.getEngineBeanName() : StandalonePlugin.DEFAULT_ENGINE_BEAN_NAME, engine);
resources.forEach(resource -> context.load(resource));
context.refresh();
context.start();
setupSpringPlugin();
setupCamelPlugin();
}
示例10: deploySingleProcess
import org.springframework.core.io.Resource; //導入依賴的package包/類
/**
* 部署單個流程定義
*
* @param resourceLoader {@link ResourceLoader}
* @param processKey 模塊名稱
* @throws IOException 找不到zip文件時
*/
private void deploySingleProcess(ResourceLoader resourceLoader, String processKey, String exportDir) throws IOException {
String classpathResourceUrl = "classpath:/deployments/" + processKey + ".bar";
logger.debug("read workflow from: {}", classpathResourceUrl);
Resource resource = resourceLoader.getResource(classpathResourceUrl);
InputStream inputStream = resource.getInputStream();
if (inputStream == null) {
logger.warn("ignore deploy workflow module: {}", classpathResourceUrl);
} else {
logger.debug("finded workflow module: {}, deploy it!", classpathResourceUrl);
ZipInputStream zis = new ZipInputStream(inputStream);
Deployment deployment = repositoryService.createDeployment().addZipInputStream(zis).deploy();
// export diagram
List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list();
for (ProcessDefinition processDefinition : list) {
WorkflowUtils.exportDiagramToFile(repositoryService, processDefinition, exportDir);
}
}
}
示例11: findNamedQueries
import org.springframework.core.io.Resource; //導入依賴的package包/類
static NamedQueries findNamedQueries(Class<?> repositoryClass) {
try {
RepositoryConfigurationExtension config = new SnowdropRepositoryConfigExtension();
String location = config.getDefaultNamedQueryLocation();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(repositoryClass.getClassLoader());
ResourceArrayPropertyEditor editor = new ResourceArrayPropertyEditor(resolver, null);
editor.setAsText(location);
Resource[] resources = (Resource[]) editor.getValue();
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setSingleton(false);
pfb.setLocations(resources);
pfb.setFileEncoding("UTF-8");
Properties properties = pfb.getObject();
return new PropertiesBasedNamedQueries(properties);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
示例12: genFileContext
import org.springframework.core.io.Resource; //導入依賴的package包/類
private static String genFileContext(List<Resource> resList, Properties properties) throws IOException {
List<Entry<Object, Object>> entryList = properties.entrySet()
.stream()
.sorted(new Comparator<Entry<Object, Object>>() {
@Override
public int compare(Entry<Object, Object> o1, Entry<Object, Object> o2) {
return o1.getKey().toString().compareTo(o2.getKey().toString());
}
})
.collect(Collectors.toList());
StringBuilder sb = new StringBuilder();
for (Resource res : resList) {
sb.append("#").append(res.getURL().getPath()).append("\n");
}
for (Entry<Object, Object> entry : entryList) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
}
return sb.toString();
}
示例13: storeResource
import org.springframework.core.io.Resource; //導入依賴的package包/類
/**
* 保存Resource到持久化,這個實現中是文件
*
* @param mediaEntity
* @return File
*/
@Override
public Resource storeResource(MediaEntity mediaEntity) throws IOException {
if (!(mediaEntity.getResource() instanceof WxMediaResource)) {
return null;
}
WxMediaResource wxMediaResource = (WxMediaResource) mediaEntity.getResource();
if (wxMediaResource.isUrlMedia()) {
return null;
}
String fileName = wxMediaResource.getFilename();
if (fileName == null) {
fileName = mediaEntity.getMediaId();
}
File file = new File(StringUtils.applyRelativePath(Type.TEMP.equals(mediaEntity.getStoreType()) ? defaultTempFilePath : defaultFilePath, fileName));
if (file.exists()) {
return new FileSystemResource(file);
}
file.createNewFile();
file.setLastModified(System.currentTimeMillis());
FileCopyUtils.copy(mediaEntity.getResource().getInputStream(), new FileOutputStream(file));
mediaEntity.setResourcePath(file.getAbsolutePath());
store(mediaEntity);
return new FileSystemResource(file);
}
示例14: shouldModifyAfterMigrationIfFileExists
import org.springframework.core.io.Resource; //導入依賴的package包/類
@Test
public void shouldModifyAfterMigrationIfFileExists() throws Exception {
//given
ChangelogVersion changelogVersion = new ChangelogVersion();
changelogVersion.setMigrationFolder("test");
Resource resourceMock = mock(Resource.class);
when(resourceMock.exists()).thenReturn(true);
when(resourcePatternResolver.getResource("classpath:/process/migrationplan/test/modification_after.json")).thenReturn(resourceMock);
ModificationCollection modificationCollectionMock = mock(ModificationCollection.class);
when(objectMapperService.convertModificationCollection(resourceMock)).thenReturn(modificationCollectionMock);
Modification modificationMock = mock(Modification.class);
when(modificationCollectionMock.getModifications()).thenReturn(Collections.singletonList(modificationMock));
ProcessInstance processInstanceMock = mock(ProcessInstance.class);
doReturn(Collections.singletonList(processInstanceMock)).when(modificationService).findProcessInstancesToModify(modificationMock);
ProcessInstanceModification processInstanceModificationMock = mock(ProcessInstanceModification.class);
doReturn(processInstanceModificationMock).when(modificationService).createProcessInstanceModification(processInstanceMock, modificationMock);
doNothing().when(modificationService).validate(modificationMock);
//when
modificationService.modifyAfterMigration(changelogVersion);
//then
verify(processInstanceModificationMock).execute();
}
示例15: setShiroConfiguration
import org.springframework.core.io.Resource; //導入依賴的package包/類
/**
* Sets shiro configuration to the path of the resource
* that points to the {@code shiro.ini} file.
*
* @param resource the resource
*/
@Autowired
public void setShiroConfiguration(@Value("${shiro.authn.config.file:classpath:shiro.ini}") final Resource resource) {
try {
if (resource.exists()) {
final String location = resource.getURI().toString();
logger.debug("Loading Shiro configuration from {}", location);
final Factory<SecurityManager> factory = new IniSecurityManagerFactory(location);
final SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
} else {
logger.debug("Shiro configuration is not defined");
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}