当前位置: 首页>>代码示例>>Java>>正文


Java Resource类代码示例

本文整理汇总了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));
}
 
开发者ID:hantsy,项目名称:spring-reactive-sample,代码行数:25,代码来源:MustacheView.java

示例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();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-skipper,代码行数:24,代码来源:PackageMetadataService.java

示例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();
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:21,代码来源:WiringTests.java

示例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;
}
 
开发者ID:Alfresco,项目名称:alfresco-remote-api,代码行数:20,代码来源:SiteSurfConfig.java

示例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);
    }
}
 
开发者ID:epam,项目名称:Lagerta,代码行数:22,代码来源:PublicKeyspacePersistenceSettings.java

示例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);
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:KeyNamingStrategy.java

示例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];
}
 
开发者ID:ampool,项目名称:monarch,代码行数:38,代码来源:ConvertUtils.java

示例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);
	}
}
 
开发者ID:youseries,项目名称:ureport,代码行数:23,代码来源:ClasspathReportProvider.java

示例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();
}
 
开发者ID:softelnet,项目名称:sponge,代码行数:24,代码来源:StandaloneEngineListener.java

示例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);
        }
    }
}
 
开发者ID:batizhao,项目名称:microservice,代码行数:27,代码来源:WorkflowProcessDefinitionService.java

示例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);
    }
}
 
开发者ID:snowdrop,项目名称:spring-data-snowdrop,代码行数:22,代码来源:CdiUtils.java

示例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();
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:21,代码来源:Log4jUtils.java

示例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);
}
 
开发者ID:FastBootWeixin,项目名称:FastBootWeixin,代码行数:31,代码来源:MapDbWxMediaStore.java

示例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();
}
 
开发者ID:satspeedy,项目名称:camunda-migrator,代码行数:25,代码来源:ModificationServiceTest.java

示例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);
    }
}
 
开发者ID:yuweijun,项目名称:cas-server-4.2.1,代码行数:24,代码来源:ShiroAuthenticationHandler.java


注:本文中的org.springframework.core.io.Resource类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。