Java Code Examples for org.springframework.core.io.Resource

The following are top voted examples for showing how to use org.springframework.core.io.Resource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-reactive-sample   File: MustacheView.java   View source code 7 votes vote down vote up
@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));
}
 
Example 2
Project: spring-cloud-skipper   File: PackageMetadataService.java   View source code 6 votes vote down vote up
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();
}
 
Example 3
Project: springboot-shiro-cas-mybatis   File: WiringTests.java   View source code 6 votes vote down vote up
@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();
}
 
Example 4
Project: alfresco-remote-api   File: SiteSurfConfig.java   View source code 6 votes vote down vote up
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;
}
 
Example 5
Project: Lagerta   File: PublicKeyspacePersistenceSettings.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Project: lams   File: KeyNamingStrategy.java   View source code 6 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example 7
Project: monarch   File: ConvertUtils.java   View source code 6 votes vote down vote up
/**
 * 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];
}
 
Example 8
Project: ureport   File: ClasspathReportProvider.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 9
Project: sponge   File: StandaloneEngineListener.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 10
Project: microservice   File: WorkflowProcessDefinitionService.java   View source code 6 votes vote down vote up
/**
 * 部署单个流程定义
 *
 * @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);
        }
    }
}
 
Example 11
Project: spring-data-snowdrop   File: CdiUtils.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 12
Project: incubator-servicecomb-java-chassis   File: Log4jUtils.java   View source code 6 votes vote down vote up
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();
}
 
Example 13
Project: FastBootWeixin   File: MapDbWxMediaStore.java   View source code 6 votes vote down vote up
/**
 * 保存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);
}
 
Example 14
Project: camunda-migrator   File: ModificationServiceTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 15
Project: cas-server-4.2.1   File: ShiroAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 16
Project: cas4.0.x-server-wechat   File: WiringTests.java   View source code 6 votes vote down vote up
@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();
}
 
Example 17
Project: gemini.blueprint   File: AbstractOsgiTests.java   View source code 6 votes vote down vote up
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;
}
 
Example 18
Project: dcmp   File: RepertoryHandler.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 19
Project: NGB-master   File: GeneControllerTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 20
Project: gemini.blueprint   File: OsgiResourceUtils.java   View source code 5 votes vote down vote up
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()]);
}
 
Example 21
Project: lams   File: PersistenceUnitReader.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: cas-5.1.0   File: WsFederationConfiguration.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 23
Project: spring-cloud-skipper   File: DefaultPackageWriter.java   View source code 5 votes vote down vote up
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;
}
 
Example 24
Project: Yoghurt   File: MybatisAutoConfiguration.java   View source code 5 votes vote down vote up
@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)");
    }
}
 
Example 25
Project: omero-ms-queue   File: FifoResourceLoaderAdapterTest.java   View source code 5 votes vote down vote up
@Test
public void absentResourceWhenNullLoci() {
    LociResourceLoader target = newRezLdr(Available);
    Optional<Resource> actual = target
                               .selectResource((ResourceLocation[])null);
    
    assertNotNull(actual);
    assertFalse(actual.isPresent());
}
 
Example 26
Project: mybatisplus-boot-starter   File: MybatisPlusAutoConfiguration.java   View source code 5 votes vote down vote up
@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)");
    }
}
 
Example 27
Project: camunda-migrator   File: DeploymentService.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: alfresco-repository   File: ScriptExecutorImpl.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 29
Project: jaffa-framework   File: SoaEventManager.java   View source code 5 votes vote down vote up
/**
    * {@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);
		}
	}
}
 
Example 30
Project: cas-5.1.0   File: SamlUtils.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 31
Project: cas-5.1.0   File: SamlUtils.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: xm-ms-entity   File: XmClasspathLepResourceService.java   View source code 5 votes vote down vote up
/**
 * {@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();
                                     }

                                 });
}
 
Example 33
Project: lemon   File: TemplateInitiator.java   View source code 5 votes vote down vote up
@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();
        }
    }
}
 
Example 34
Project: alfresco-repository   File: ResourceFinder.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 35
Project: sample-SpringBoot-payments-app   File: SwaggerJsonApi.java   View source code 5 votes vote down vote up
@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();
 
Example 36
Project: cas4.0.x-server-wechat   File: ResourceCRLRevocationChecker.java   View source code 5 votes vote down vote up
/**
 * 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.");
    }
}
 
Example 37
Project: incubator-servicecomb-java-chassis   File: PaaSResourceUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 38
Project: dcmp   File: ConfigurerHandlerImpl.java   View source code 5 votes vote down vote up
@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);
    }
}
 
Example 39
Project: azure-service-broker-client   File: VcapParserTest.java   View source code 5 votes vote down vote up
@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);
	}
}
 
Example 40
Project: testing-101   File: CustomerClientWiremockTest.java   View source code 5 votes vote down vote up
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;
}