Java 类org.springframework.core.io.Resource 实例源码

项目:spring-reactive-sample    文件:MustacheView.java   
@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));
}
项目:spring-cloud-skipper    文件:PackageMetadataService.java   
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();
}
项目:springboot-shiro-cas-mybatis    文件:WiringTests.java   
@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();
}
项目:alfresco-remote-api    文件:SiteSurfConfig.java   
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;
}
项目:Lagerta    文件:PublicKeyspacePersistenceSettings.java   
/**
 * 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);
    }
}
项目:lams    文件:KeyNamingStrategy.java   
/**
 * 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);
        }
    }
}
项目:monarch    文件:ConvertUtils.java   
/**
 * 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];
}
项目:ureport    文件:ClasspathReportProvider.java   
@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);
    }
}
项目:sponge    文件:StandaloneEngineListener.java   
/**
 * 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();
}
项目:microservice    文件:WorkflowProcessDefinitionService.java   
/**
 * 部署单个流程定义
 *
 * @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);
        }
    }
}
项目:spring-data-snowdrop    文件:CdiUtils.java   
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);
    }
}
项目:incubator-servicecomb-java-chassis    文件:Log4jUtils.java   
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();
}
项目:FastBootWeixin    文件:MapDbWxMediaStore.java   
/**
 * 保存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);
}
项目:camunda-migrator    文件:ModificationServiceTest.java   
@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();
}
项目:cas-server-4.2.1    文件:ShiroAuthenticationHandler.java   
/**
 * 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);
    }
}
项目:cas4.0.x-server-wechat    文件:WiringTests.java   
@Before
public void setUp() {
    applicationContext = new XmlWebApplicationContext();
    applicationContext.setConfigLocations(new String[]{
            "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();
}
项目:gemini.blueprint    文件:AbstractOsgiTests.java   
private Resource[] locateBundles() {
    Resource[] testFrameworkBundles = getTestFrameworkBundles();
    Resource[] testBundles = getTestBundles();

    if (testFrameworkBundles == null) {
        testFrameworkBundles = new Resource[0];
    }
    if (testBundles == null) {
        testBundles = new Resource[0];
    }

    Resource[] allBundles = new Resource[testFrameworkBundles.length + testBundles.length];
    System.arraycopy(testFrameworkBundles, 0, allBundles, 0, testFrameworkBundles.length);
    System.arraycopy(testBundles, 0, allBundles, testFrameworkBundles.length, testBundles.length);
    return allBundles;
}
项目:dcmp    文件:RepertoryHandler.java   
/**
 * Init git repertory
 */
void initRepo() throws SysException {
    try {
        Resource repoDir = buildRepoDir();

        if (repoDir.getFile().exists()) {
            FileUtils.deleteDirectory(repoDir.getFile());
        } else {
            repoDir.getFile().mkdirs();
        }

        repertoryService.cloneRepo(repoDir.getFile());
    } catch (Exception e) {
        throw new SysException(e);
    }
}
项目:NGB-master    文件:GeneControllerTest.java   
@Before
public void setup() throws Exception {
    super.setup();

    Resource resource = context.getResource("classpath:templates/A3.fa");

    ReferenceRegistrationRequest request = new ReferenceRegistrationRequest();
    request.setName("a3");
    request.setPath(resource.getFile().getPath());
    request.setType(BiologicalDataItemResourceType.FILE);

    testReference = referenceManager.registerGenome(request);
    Assert.assertNotNull(testReference);
    testChromosome = testReference.getChromosomes().get(0);
    referenceId = testReference.getId();
}
项目:gemini.blueprint    文件:OsgiResourceUtils.java   
public static Resource[] convertURLEnumerationToResourceArray(Enumeration<URL> enm) {
    Set<UrlResource> resources = new LinkedHashSet<UrlResource>(4);
    while (enm != null && enm.hasMoreElements()) {
        resources.add(new UrlResource(enm.nextElement()));
    }
    return (Resource[]) resources.toArray(new Resource[resources.size()]);
}
项目:lams    文件:PersistenceUnitReader.java   
/**
 * Parse the validated document and add entries to the given unit info list.
 */
protected List<SpringPersistenceUnitInfo> parseDocument(
        Resource resource, Document document, List<SpringPersistenceUnitInfo> infos) throws IOException {

    Element persistence = document.getDocumentElement();
    String version = persistence.getAttribute(PERSISTENCE_VERSION);
    URL rootUrl = determinePersistenceUnitRootUrl(resource);

    List<Element> units = DomUtils.getChildElementsByTagName(persistence, PERSISTENCE_UNIT);
    for (Element unit : units) {
        infos.add(parsePersistenceUnitInfo(unit, version, rootUrl));
    }

    return infos;
}
项目:cas-5.1.0    文件:WsFederationConfiguration.java   
/**
 * getSigningCredential loads up an X509Credential from a file.
 *
 * @param resource the signing certificate file
 * @return an X509 credential
 */
private static Credential getSigningCredential(final Resource resource) {
    try(InputStream inputStream = resource.getInputStream()) {
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
        final Credential publicCredential = new BasicX509Credential(certificate);
        LOGGER.debug("getSigningCredential: key retrieved.");
        return publicCredential;
    } catch (final Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return null;
}
项目:spring-cloud-skipper    文件:DefaultPackageWriter.java   
private String getDefaultTemplate() {
    Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/io/generic-template.yml");
    String genericTempateData = null;
    try {
        genericTempateData = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
    }
    catch (IOException e) {
        throw new IllegalArgumentException("Can't load generic template", e);
    }
    return genericTempateData;
}
项目:Yoghurt    文件:MybatisAutoConfiguration.java   
@PostConstruct
public void checkConfigFileExists() {
    if (this.properties.isCheckConfigLocation()) {
        Resource resource = this.resourceLoader
                .getResource(this.properties.getConfig());
        Assert.state(resource.exists(),
                "Cannot find config location: " + resource
                        + " (please add config file or check your Mybatis "
                        + "configuration)");
    }
}
项目:omero-ms-queue    文件:FifoResourceLoaderAdapterTest.java   
@Test
public void absentResourceWhenNullLoci() {
    LociResourceLoader target = newRezLdr(Available);
    Optional<Resource> actual = target
                               .selectResource((ResourceLocation[])null);

    assertNotNull(actual);
    assertFalse(actual.isPresent());
}
项目:mybatisplus-boot-starter    文件:MybatisPlusAutoConfiguration.java   
@PostConstruct
public void checkConfigFileExists() {
    if (this.properties.isCheckConfigLocation() && StringUtils.hasText(this.properties.getConfigLocation())) {
        Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());
        Assert.state(resource.exists(), "Cannot find config location: " + resource
                + " (please add config file or check your Mybatis configuration)");
    }
}
项目:camunda-migrator    文件:DeploymentService.java   
/**
 * Checks if the given version is already deployment.
 *
 * @param changelogVersion changelogVersion
 * @param zipResource zipResource
 * @return true, if already deployed
 * @throws IOException exception
 */
protected boolean isVersionAlreadyDeployed(ChangelogVersion changelogVersion, Resource zipResource) {
  final List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().versionTag(changelogVersion.getVersionTag()).list();
  if (processDefinitions.isEmpty()) {
    return false;
  }

  final List<String> hashValuesFromDB = processDefinitionService.extractBPMNHashValuesFromEngine();
  final List<String> hashValuesFromFile = zipResourceService.extractHashValuesFromZipEntries(changelogVersion, zipResource);
  return hashValuesFromDB.containsAll(hashValuesFromFile);
}
项目:alfresco-repository    文件:ScriptExecutorImpl.java   
/**
 * Replaces the dialect placeholder in the script URL and attempts to find a file for
 * it.  If not found, the dialect hierarchy will be walked until a compatible script is
 * found.  This makes it possible to have scripts that are generic to all dialects.
 * 
 * @return Returns an input stream onto the script, otherwise null
 */
private InputStream getScriptInputStream(Class dialectClazz, String scriptUrl) throws Exception
{
    Resource resource = getDialectResource(dialectClazz, scriptUrl);
    if (resource == null)
    {
        return null;
    }
    return resource.getInputStream();
}
项目:jaffa-framework    文件:SoaEventManager.java   
/**
    * {@inheritDoc}
    */
@Override
public void registerResource(Resource resource, String context, String variation) throws JAXBException, SAXException, IOException {
    SoaEvents soaEvents = JAXBHelper.unmarshalConfigFile(SoaEvents.class, resource, CONFIGURATION_SCHEMA_FILE);

    if (soaEvents != null) {
        for (SoaEventInfo soaEventInfo : soaEvents.getSoaEvent()) {
            ContextKey contextKey = new ContextKey(soaEventInfo.getName(), resource.getURI().toString(), variation, context);
            registerSoaEventInfo(contextKey, soaEventInfo);
        }
    }
}
项目:cas-5.1.0    文件:SamlUtils.java   
/**
 * Read certificate x 509 certificate.
 *
 * @param resource the resource
 * @return the x 509 certificate
 */
public static X509Certificate readCertificate(final Resource resource) {
    try (InputStream in = resource.getInputStream()) {
        return CertUtil.readCertificate(in);
    } catch (final Exception e) {
        throw new RuntimeException("Error reading certificate " + resource, e);
    }
}
项目:cas-5.1.0    文件:SamlUtils.java   
/**
 * Build signature validation filter if needed.
 *
 * @param signatureResourceLocation the signature resource location
 * @return the metadata filter
 * @throws Exception the exception
 */
public static SignatureValidationFilter buildSignatureValidationFilter(final Resource signatureResourceLocation) throws Exception {
    if (!ResourceUtils.doesResourceExist(signatureResourceLocation)) {
        LOGGER.warn("Resource [{}] cannot be located", signatureResourceLocation);
        return null;
    }

    final List<KeyInfoProvider> keyInfoProviderList = new ArrayList<>();
    keyInfoProviderList.add(new RSAKeyValueProvider());
    keyInfoProviderList.add(new DSAKeyValueProvider());
    keyInfoProviderList.add(new DEREncodedKeyValueProvider());
    keyInfoProviderList.add(new InlineX509DataProvider());

    LOGGER.debug("Attempting to resolve credentials from [{}]", signatureResourceLocation);
    final BasicCredential credential = buildCredentialForMetadataSignatureValidation(signatureResourceLocation);
    LOGGER.info("Successfully resolved credentials from [{}]", signatureResourceLocation);

    LOGGER.debug("Configuring credential resolver for key signature trust engine @ [{}]", credential.getCredentialType().getSimpleName());
    final StaticCredentialResolver resolver = new StaticCredentialResolver(credential);
    final BasicProviderKeyInfoCredentialResolver keyInfoResolver = new BasicProviderKeyInfoCredentialResolver(keyInfoProviderList);
    final ExplicitKeySignatureTrustEngine trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyInfoResolver);

    LOGGER.debug("Adding signature validation filter based on the configured trust engine");
    final SignatureValidationFilter signatureValidationFilter = new SignatureValidationFilter(trustEngine);
    signatureValidationFilter.setRequireSignedRoot(false);
    LOGGER.debug("Added metadata SignatureValidationFilter with signature from [{}]", signatureResourceLocation);
    return signatureValidationFilter;
}
项目:xm-ms-entity    文件:XmClasspathLepResourceService.java   
/**
 * {@inheritDoc}
 */
@Override
public LepResource getResource(LepResourceKey resourceKey) {
    Objects.requireNonNull(resourceKey, "resourceKey can't be null");

    log.debug("Getting LEP resource for key {}", resourceKey);

    final Resource scriptResource = getScriptResource(resourceKey);
    if (!scriptResource.exists()) {
        log.debug("No LEP resource for key {}", resourceKey);
        return null;
    }

    // build descriptor
    LepResourceDescriptor descriptor = getLepResourceDescriptor(resourceKey, scriptResource);
    log.debug("LEP resource for key {} found, descriptor: {}", resourceKey, descriptor);

    return new ScriptLepResource(descriptor, ScriptLepResource.DEFAULT_ENCODING,
                                 new InputStreamSupplier() {

                                     /**
                                      * {@inheritDoc}
                                      */
                                     @Override
                                     public InputStream getInputStream() throws IOException {
                                         return scriptResource.getInputStream();
                                     }

                                 });
}
项目:lemon    文件:TemplateInitiator.java   
@PostConstruct
public void init() throws Exception {
    File dir = new File(baseDir + "/cms/template/default");

    if (dir.exists()) {
        return;
    }

    dir.mkdirs();

    Resource[] resources = applicationContext
            .getResources("classpath:/cms/template/default/*");

    if (resources == null) {
        logger.info("cannot find default template for cms.");

        return;
    }

    for (Resource resource : resources) {
        File file = new File(dir, resource.getFilename());
        FileOutputStream fos = new FileOutputStream(file);

        try {
            FileCopyUtils.copy(resource.getInputStream(), fos);
            fos.flush();
        } finally {
            fos.close();
        }
    }
}
项目:alfresco-repository    文件:ResourceFinder.java   
/**
 * Gets an array of resources matching the given location patterns.
 * 
 * @param locationPatterns
 *            the location patterns
 * @return the matching resources, ordered by locationPattern index and location in the classpath
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public Resource[] getResources(String... locationPatterns) throws IOException
{
    List<Resource> resources = new LinkedList<Resource>();
    for (String locationPattern : locationPatterns)
    {
        resources.addAll(Arrays.asList(getResources(locationPattern)));
    }
    Resource[] resourceArray = new Resource[resources.size()];
    resources.toArray(resourceArray);
    return resourceArray;
}
项目:sample-SpringBoot-payments-app    文件:SwaggerJsonApi.java   
@ApiOperation(value = "Download public/swagger/swagger.json", notes = "", response = Resource.class, tags={  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "File downloaded", response = Resource.class) })

@RequestMapping(value = "/swagger.json",
    produces = { "application/json" }, 
    consumes = { "application/json" },
    method = RequestMethod.GET)
ResponseEntity<Resource> swaggerSwaggerJson();
项目:cas4.0.x-server-wechat    文件:ResourceCRLRevocationChecker.java   
/**
 * Creates a new instance using the specified resources for CRL data.
 *
 * @param crls Resources containing CRL data.  MUST NOT be null and MUST have
 * at least one non-null element.
 */
public CRLFetcher(final Resource[] crls) {
    if (crls == null) {
        throw new IllegalArgumentException("CRL resources cannot be null.");
    }
    this.resources = new ArrayList<Resource>();
    for (Resource r : crls) {
        if (r != null) {
            this.resources.add(r);
        }
    }
    if (this.resources.size() == 0) {
        throw new IllegalArgumentException("Must provide at least one non-null CRL resource.");
    }
}
项目:incubator-servicecomb-java-chassis    文件:PaaSResourceUtils.java   
public static List<Resource> getSortedResources(String locationPattern, String suffix) {
  if (StringUtils.isEmpty(locationPattern)) {
    throw new RuntimeException("Resource path must not be null or empty");
  }

  if (!locationPattern.endsWith(suffix)) {
    throw new RuntimeException("Resource path must ends with " + suffix);
  }

  String prefix = locationPattern.substring(0, locationPattern.length() - suffix.length());

  List<Resource> resList = PaaSResourceUtils.getResources(locationPattern, prefix + ".*" + suffix);
  sortResources(resList, suffix);
  return resList;
}
项目:dcmp    文件:ConfigurerHandlerImpl.java   
@Override
public Resource[] findProperties() throws SysException {
    try {
        Resource resource = new FileSystemResource(Configurer.filePath);
        File[] files = resource.getFile().listFiles();

        if (files == null || files.length == 0) {
            return null;
        }

        Resource[] resourceArray = new Resource[files.length];
        String suffix = "properties";

        for (int i = 0; i < files.length; i++) {
            String name = files[i].getName().substring(files[i].getName().lastIndexOf(".") + 1);

            if (!suffix.equalsIgnoreCase(name)) {
                continue;
            }

            resourceArray[i] = new FileSystemResource(files[i].getPath());
        }
        return resourceArray;
    } catch (Exception e) {
        throw new SysException(e);
    }
}
项目:azure-service-broker-client    文件:VcapParserTest.java   
@Test
public void testVcapSingleService()
{
    Resource resource = new ClassPathResource("/vcap1.json");
    String content;
    try
    {
        content = new String(Files.readAllBytes(Paths.get(resource.getURI())));
        VcapResult result = parser.parse(content); 
        VcapPojo[] pojos = result.getPojos();
        assertNotNull(pojos);
        assertEquals(1, pojos.length);
        VcapPojo pojo = pojos[0];

        LOG.debug("pojo = " + pojo);
        assertEquals(5, pojo.getCredentials().size());
        assertEquals(2, pojo.getTags().length);
        assertEquals(0, pojo.getVolumeMounts().length);
        assertEquals("azure-sqldb", pojo.getLabel());
        assertEquals("provider", pojo.getProvider());
        assertEquals("azure-sqldb", pojo.getServiceBrokerName());
        assertEquals("myazuredb-service", pojo.getServiceInstanceName());
        assertEquals("basic", pojo.getServicePlan());
        assertEquals("drain_url", pojo.getSyslogDrainUrl());
        assertEquals("Azure", pojo.getTags()[0]);
        assertEquals("SQL", pojo.getTags()[1]);

        assertEquals("userid", pojo.getCredentials().get("administratorLogin"));
        assertEquals("password", pojo.getCredentials().get("administratorLoginPassword"));
        assertEquals("jdbc:sqlserver://hostname:1433;database=dbname;user=user;password=pw", pojo.getCredentials().get("jdbcUrl"));
        assertEquals("sql-server-name", pojo.getCredentials().get("sqlServerName"));
        assertEquals("db-name", pojo.getCredentials().get("sqldbName"));
    } 
    catch (IOException e)
    {
        LOG.error("Error reading json file", e);
    }
}
项目:testing-101    文件:CustomerClientWiremockTest.java   
private String asJson(Resource resource) {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
        Stream<String> lines = bufferedReader.lines();
        return lines.collect(Collectors.joining());
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}