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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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: tensorflow-spring-cloud-stream-app-starters   File: TensorFlowService.java   Source Code and License 6 votes vote down vote up
public TensorFlowService(Resource modelLocation) throws IOException {
	try (InputStream is = modelLocation.getInputStream()) {
		graph = new Graph();
		logger.info("Loading TensorFlow graph model: " + modelLocation);
		graph.importGraphDef(toByteArray(buffer(is)));
		logger.info("TensorFlow Graph Model Ready To Serve!");
	}
}
 
Example 21
Project: gemini.blueprint   File: OsgiResourceUtils.java   Source Code and License 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 22
Project: lams   File: PersistenceUnitReader.java   Source Code and License 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 23
Project: cas-5.1.0   File: WsFederationConfiguration.java   Source Code and License 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 24
Project: spring-cloud-skipper   File: DefaultPackageWriter.java   Source Code and License 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 25
Project: Yoghurt   File: MybatisAutoConfiguration.java   Source Code and License 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 26
Project: omero-ms-queue   File: FifoResourceLoaderAdapterTest.java   Source Code and License 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 27
Project: mybatisplus-boot-starter   File: MybatisPlusAutoConfiguration.java   Source Code and License 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 28
Project: camunda-migrator   File: DeploymentService.java   Source Code and License 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 29
Project: alfresco-repository   File: ScriptExecutorImpl.java   Source Code and License 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 30
Project: jaffa-framework   File: SoaEventManager.java   Source Code and License 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 31
Project: cas-5.1.0   File: SamlUtils.java   Source Code and License 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 32
Project: cas-5.1.0   File: SamlUtils.java   Source Code and License 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 33
Project: xm-ms-entity   File: XmClasspathLepResourceService.java   Source Code and License 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 34
Project: lemon   File: TemplateInitiator.java   Source Code and License 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 35
Project: alfresco-repository   File: ResourceFinder.java   Source Code and License 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 36
Project: sample-SpringBoot-payments-app   File: SwaggerJsonApi.java   Source Code and License 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 37
Project: cas4.0.x-server-wechat   File: ResourceCRLRevocationChecker.java   Source Code and License 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 38
Project: incubator-servicecomb-java-chassis   File: PaaSResourceUtils.java   Source Code and License 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 39
Project: dcmp   File: ConfigurerHandlerImpl.java   Source Code and License 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 40
Project: azure-service-broker-client   File: VcapParserTest.java   Source Code and License 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 41
Project: testing-101   File: CustomerClientWiremockTest.java   Source Code and License 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;
}
 
Example 42
Project: gemini.blueprint   File: OsgiBundleResourcePatternResolver.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * Overrides the default check up since computing the URL can be fairly expensive operation as there is no caching
 * (due to the framework dynamic nature).
 */
protected boolean isJarResource(Resource resource) throws IOException {
	if (resource instanceof OsgiBundleResource) {
		// check the resource type
		OsgiBundleResource bundleResource = (OsgiBundleResource) resource;
		// if it's known, then it's not a jar
		if (bundleResource.getSearchType() != OsgiResourceUtils.PREFIX_TYPE_UNKNOWN) {
			return false;
		}
		// otherwise the normal parsing occur
	}
	return super.isJarResource(resource);
}
 
Example 43
Project: gradle-java-monkey-patch   File: ClassPathXmlApplicationContext.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new ClassPathXmlApplicationContext with the given parent,
 * loading the definitions from the given XML files and automatically
 * refreshing the context.
 * @param paths array of relative (or absolute) paths within the class path
 * @param clazz the class to load resources with (basis for the given paths)
 * @param parent the parent context
 * @throws BeansException if context creation failed
 * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String, Class)
 * @see org.springframework.context.support.GenericApplicationContext
 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
 */
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, ApplicationContext parent)
		throws BeansException {

	super(parent);
	Assert.notNull(paths, "Path array must not be null");
	Assert.notNull(clazz, "Class argument must not be null");
	this.configResources = new Resource[paths.length];
	for (int i = 0; i < paths.length; i++) {
		this.configResources[i] = new ClassPathResource(paths[i], clazz);
	}
	refresh();
}
 
Example 44
Project: mybatis-plus-mini   File: MybatisMapperRefresh.java   Source Code and License 5 votes vote down vote up
/**
 * see  com.baomidou.mybatisplus.spring.MybatisMapperRefresh#MybatisMapperRefresh(org.apache.ibatis.session.SqlSessionFactory, int, int, boolean)
 *
 * @param mapperLocations
 * @param sqlSessionFactory
 * @param delaySeconds
 * @param sleepSeconds
 */
public MybatisMapperRefresh(Resource[] mapperLocations, SqlSessionFactory sqlSessionFactory, int delaySeconds,
                            int sleepSeconds) {
    this.mapperLocations = mapperLocations.clone();
    this.sqlSessionFactory = sqlSessionFactory;
    this.delaySeconds = delaySeconds;
    this.sleepSeconds = sleepSeconds;
    this.configuration = sqlSessionFactory.getConfiguration();
    this.run();
}
 
Example 45
Project: camunda-migrator   File: ModificationServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldNotModifyIfFileNotExists() throws Exception {
  //given
  ChangelogVersion changelogVersion = new ChangelogVersion();
  changelogVersion.setMigrationFolder("test");
  Resource resourceMock = mock(Resource.class);
  when(resourceMock.exists()).thenReturn(false);
  when(resourcePatternResolver.getResource("classpath:/process/migrationplan/test/modification_before.json")).thenReturn(resourceMock);
  //when
  modificationService.modifyBeforeMigration(changelogVersion);

  //then
  verify(objectMapperService, never()).convertModificationCollection(any());
  verify(modificationService, never()).createProcessInstanceModification(any(), any());
}
 
Example 46
Project: xm-commons   File: XmLepResourceService.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public LepResourceDescriptor getResourceDescriptor(ContextsHolder contextsHolder, LepResourceKey resourceKey) {
    Objects.requireNonNull(resourceKey, "resourceKey can't be null");
    Resource scriptResource = getScriptResource(contextsHolder, resourceKey);
    if (!scriptResource.exists()) {
        log.debug("No LEP resource for key {}", resourceKey);
        return null;
    }
    return getLepResourceDescriptor(resourceKey, scriptResource);
}
 
Example 47
Project: simple-openid-provider   File: OAuth2Configuration.java   Source Code and License 5 votes vote down vote up
@Bean
public JwkSetLoader jwkSetLoader() {
	return () -> {
		try {
			Resource jwkSetResource = this.resourceLoader.getResource(JWK_SET_LOCATION);
			String jwkSetJson = new String(FileCopyUtils.copyToByteArray(jwkSetResource.getInputStream()));

			return JWKSet.parse(jwkSetJson);
		}
		catch (IOException | ParseException e) {
			throw new RuntimeException(e);
		}
	};
}
 
Example 48
Project: omero-ms-queue   File: FifoResourceLoaderAdapterTest.java   Source Code and License 5 votes vote down vote up
@Theory
public void absentResourceWhenNoResourceAvailable(String a0, String a1) {
    assumeFalse(allNullOrEmpty(a0, a1));  // avoid unnecessary tests
    assumeFalse(anyAvailable(a0, a1));
    
    Optional<Resource> actual = invoke(false, a0, a1);
    
    assertNotNull(actual);
    assertFalse(actual.isPresent());
}
 
Example 49
Project: mylion-mvn   File: MydogTemplateLoader.java   Source Code and License 5 votes vote down vote up
@Override
public long getLastModified(Object templateSource) {
	Resource resource = (Resource) templateSource;
	try {
		return resource.lastModified();
	} catch (IOException ex) {

		return -1;
	}
}
 
Example 50
Project: NGB-master   File: GffManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testLoadExonsInViewPort() throws InterruptedException, NoSuchAlgorithmException, FeatureIndexException,
        IOException {
    Resource resource = context.getResource(GENES_SORTED_GTF_PATH);

    FeatureIndexedFileRegistrationRequest request = new FeatureIndexedFileRegistrationRequest();
    request.setReferenceId(referenceId);
    request.setPath(resource.getFile().getAbsolutePath());

    GeneFile geneFile = gffManager.registerGeneFile(request);
    Assert.assertNotNull(geneFile);
    Assert.assertNotNull(geneFile.getId());

    double time1 = Utils.getSystemTimeMilliseconds();
    List<Block> exons = gffManager.loadExonsInViewPort(geneFile.getId(), testChromosome.getId(),
            TEST_CENTER_POSITION, TEST_VIEW_PORT_SIZE, TEST_INTRON_LENGTH);
    double time2 = Utils.getSystemTimeMilliseconds();
    Assert.assertFalse(exons.isEmpty());
    logger.info("Loading exons took {} ms", time2 - time1);
    List<Block> exonsBelow = exons.stream()
            .filter(e -> e.getEndIndex() < TEST_CENTER_POSITION)
            .collect(Collectors.toList());
    List<Block> exonsAbove = exons.stream()
            .filter(e -> e.getStartIndex() > TEST_CENTER_POSITION)
            .collect(Collectors.toList());
    Assert.assertFalse(exonsBelow.isEmpty());
    Assert.assertFalse(exonsAbove.isEmpty());

    testOverlapping(exons);

    final Map<String, Pair<Integer, Integer>> metaMap = fileManager.loadIndexMetadata(geneFile);
    Pair<Integer, Integer> bounds = metaMap.get(testChromosome.getName());
    if (bounds == null) {
        bounds = metaMap.get(Utils.changeChromosomeName(testChromosome.getName()));
    }

    testFillRange(exonsBelow, TEST_VIEW_PORT_SIZE / 2, TEST_CENTER_POSITION, false, bounds.getLeft());
    testFillRange(exonsAbove, TEST_VIEW_PORT_SIZE / 2, TEST_CENTER_POSITION, true, bounds.getRight());
}
 
Example 51
Project: spring-reactive-sample   File: MustacheView.java   Source Code and License 5 votes vote down vote up
private Resource resolveResource() {
    Resource resource = getApplicationContext().getResource(getUrl());
    if (resource == null || !resource.exists()) {
        return null;
    }
    return resource;
}
 
Example 52
Project: rekit-game   File: LevelManager.java   Source Code and License 5 votes vote down vote up
/**
 * Add a level by resource.
 *
 * @param level
 *            the resource
 */
private static void addArcadeLevel(Resource level) {
	RWContainer<String> path = new RWContainer<>();
	LambdaUtil.invoke(() -> path.set(level.getURL().getPath()));
	String[] split = null;
	if (path.get() == null || (split = path.get().split("/")) == null || split[split.length - 2].equals("levels")) {
		LambdaUtil.invoke(() -> LevelManager.addArcadeLevel(level, LevelManager.GROUP_UNKNOWN));
	} else {
		final String group = split[split.length - 2];
		LambdaUtil.invoke(() -> LevelManager.addArcadeLevel(level, group));
	}
}
 
Example 53
Project: inception-serving-sb   File: Application.java   Source Code and License 5 votes vote down vote up
@Bean
public List<String> tfModelLabels(@Value("${tf.labelsPath}") String labelsPath) throws IOException {
    Resource labelsRes = getResource(labelsPath);
    log.info("Loaded model labels");
 return IOUtils.readLines(labelsRes.getInputStream(), Charset.forName("UTF-8")).stream()
        .map(label -> label.substring(label.contains(":") ? label.indexOf(":")+1 : 0)).collect(Collectors.toList());
}
 
Example 54
Project: jaffa-framework   File: DroolsManagerTest.java   Source Code and License 5 votes vote down vote up
/**
 * tests the registering of drool method
 * @throws Exception
 */
@Test
public void testRegisterDrool() throws Exception{
    Resource resource = pathMatchingResourcePatternResolver.getResource(CORE_DRL_PATH);
    //Test
    droolsManager.registerDrool(resource, VariationContext.DEFAULT_VARIATION);
    //verify
    assertNotNull(droolsManager.getDroolsFiles().get(new RuleAgentKey(SERVICE_NAME, VariationContext.DEFAULT_VARIATION)));
}
 
Example 55
Project: lemon   File: AutoDeployer.java   Source Code and License 4 votes vote down vote up
public void setDeploymentResources(Resource[] deploymentResources) {
    this.deploymentResources = deploymentResources;
}
 
Example 56
Project: cas-5.1.0   File: MaxmindProperties.java   Source Code and License 4 votes vote down vote up
public Resource getCityDatabase() {
    return cityDatabase;
}
 
Example 57
Project: spring-cloud-skipper   File: PackageServiceTests.java   Source Code and License 4 votes vote down vote up
@Test
public void upload() throws Exception {
	// Create throw away repository, treated to be a 'local' database repo by default for now.
	Repository repository = new Repository();
	repository.setName("database-repo");
	repository.setUrl("http://example.com/repository/");
	this.repositoryRepository.save(repository);

	// Package log 9.9.9 should not exist, since it hasn't been uploaded yet.
	PackageMetadata packageMetadata = packageMetadataRepository.findByNameAndVersionByMaxRepoOrder("log", "9.9.9");
	assertThat(packageMetadata).isNull();

	UploadRequest uploadProperties = new UploadRequest();
	uploadProperties.setRepoName("local");
	uploadProperties.setName("log");
	uploadProperties.setVersion("9.9.9");
	uploadProperties.setExtension("zip");
	Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/server/service/log-9.9.9.zip");
	assertThat(resource.exists()).isTrue();
	byte[] originalPackageBytes = StreamUtils.copyToByteArray(resource.getInputStream());
	assertThat(originalPackageBytes).isNotEmpty();
	Assert.isTrue(originalPackageBytes.length != 0,
			"PackageServiceTests.Assert.isTrue: Package file as bytes must not be empty");
	uploadProperties.setPackageFileAsBytes(originalPackageBytes);

	// Upload new package
	assertThat(packageService).isNotNull();
	PackageMetadata uploadedPackageMetadata = this.packageService.upload(uploadProperties);
	assertThat(uploadedPackageMetadata.getName().equals("log")).isTrue();
	assertThat(uploadedPackageMetadata.getVersion().equals("9.9.9")).isTrue();
	assertThat(uploadedPackageMetadata.getId()).isNotNull();

	// Retrieve new package
	PackageMetadata retrievedPackageMetadata = packageMetadataRepository.findByNameAndVersionByMaxRepoOrder("log",
			"9.9.9");
	assertThat(retrievedPackageMetadata.getName().equals("log")).isTrue();
	assertThat(retrievedPackageMetadata.getVersion().equals("9.9.9")).isTrue();
	assertThat(retrievedPackageMetadata).isNotNull();
	assertThat(retrievedPackageMetadata.getPackageFile().getPackageBytes()).isNotNull();
	byte[] retrievedPackageBytes = retrievedPackageMetadata.getPackageFile().getPackageBytes();
	assertThat(originalPackageBytes).isEqualTo(retrievedPackageBytes);

	// Check that package can be deserialized from the database.
	Package downloadedPackage = packageService.downloadPackage(retrievedPackageMetadata);
	assertThat(downloadedPackage.getMetadata()).isEqualToIgnoringGivenFields(retrievedPackageMetadata);
	assertThat(downloadedPackage.getTemplates()).isNotNull();
	assertThat(downloadedPackage.getConfigValues()).isNotNull();

}
 
Example 58
Project: NGB-master   File: GffManagerTest.java   Source Code and License 4 votes vote down vote up
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testLoadGenesTranscript() throws IOException, InterruptedException, FeatureIndexException,
        NoSuchAlgorithmException, ExternalDbUnavailableException {
    MockitoAnnotations.initMocks(this);
    String fetchRes1 = readFile("ensembl_id_ENSG00000177663.json");
    String fetchRes2 = readFile("uniprot_id_ENST00000319363.xml");
    String fetchRes3 = readFile("uniprot_id_ENST00000319363.xml");
    Mockito.when(
            httpDataManager.fetchData(Mockito.any(), Mockito.any(ParameterNameValue[].class)))
            .thenReturn(fetchRes1)
            .thenReturn(fetchRes2)
            .thenReturn(fetchRes3);


    Chromosome otherChromosome = EntityHelper.createNewChromosome("22");
    otherChromosome.setSize(TEST_CHROMOSOME_SIZE);
    Reference otherReference = EntityHelper.createNewReference(otherChromosome,
            referenceGenomeManager.createReferenceId());

    referenceGenomeManager.register(otherReference);
    Long otherReferenceId = otherReference.getId();

    Resource resource = context.getResource("classpath:templates/Homo_sapiens.GRCh38.83.sorted.chr21-22.gtf");


    FeatureIndexedFileRegistrationRequest request = new FeatureIndexedFileRegistrationRequest();
    request.setReferenceId(otherReferenceId);
    request.setPath(resource.getFile().getAbsolutePath());

    GeneFile geneFile = gffManager.registerGeneFile(request);
    Assert.assertNotNull(geneFile);
    Assert.assertNotNull(geneFile.getId());

    Track<Gene> track = new Track<>();
    track.setId(geneFile.getId());
    track.setStartIndex(START_INDEX_ASTRA);
    track.setEndIndex(END_INDEX_ASTRA);
    track.setChromosome(otherChromosome);
    track.setScaleFactor(FULL_QUERY_SCALE_FACTOR);
    try {
        Track<GeneTranscript> featureList = gffManager.loadGenesTranscript(track, null, null);
        Assert.assertNotNull(featureList);
        Assert.assertFalse(featureList.getBlocks().isEmpty());
        Gene testGene = featureList.getBlocks().get(0);
        Assert.assertNotNull(testGene);
        Assert.assertFalse(testGene.getTranscripts().isEmpty());
        Transcript testTranscript = testGene.getTranscripts().get(1);

        Assert.assertTrue(testTranscript.getBioType().equals(PROTEIN_CODING));

        Assert.assertFalse(testTranscript.getDomain().isEmpty());
        Assert.assertFalse(testTranscript.getExon().isEmpty());
        Assert.assertFalse(testTranscript.getSecondaryStructure().isEmpty());
        Assert.assertFalse(testTranscript.getPdb().isEmpty());
    } catch (GeneReadingException e) {
        logger.info("database unavailable");
    }
}
 
Example 59
Project: gemini.blueprint   File: ClassSpaceWildcardTest.java   Source Code and License 4 votes vote down vote up
public void testAllClassPathWOWildcardAtFolderLevel() throws Exception {
	Resource res[] = patternLoader.getResources("classpath*:META-INF/");
	// only the bundle and its fragments should be considered (since no other META-INF/ is available on the classpath)
	assertEquals("not enough packages found", 3, res.length);
	printPathWithinContext(res);
}
 
Example 60
Project: lams   File: VelocityEngineFactory.java   Source Code and License 4 votes vote down vote up
/**
 * Initialize a Velocity resource loader for the given VelocityEngine:
 * either a standard Velocity FileResourceLoader or a SpringResourceLoader.
 * <p>Called by {@code createVelocityEngine()}.
 * @param velocityEngine the VelocityEngine to configure
 * @param resourceLoaderPath the path to load Velocity resources from
 * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader
 * @see SpringResourceLoader
 * @see #initSpringResourceLoader
 * @see #createVelocityEngine()
 */
protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) {
	if (isPreferFileSystemAccess()) {
		// Try to load via the file system, fall back to SpringResourceLoader
		// (for hot detection of template changes, if possible).
		try {
			StringBuilder resolvedPath = new StringBuilder();
			String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
			for (int i = 0; i < paths.length; i++) {
				String path = paths[i];
				Resource resource = getResourceLoader().getResource(path);
				File file = resource.getFile();  // will fail if not resolvable in the file system
				if (logger.isDebugEnabled()) {
					logger.debug("Resource loader path [" + path + "] resolved to file [" + file.getAbsolutePath() + "]");
				}
				resolvedPath.append(file.getAbsolutePath());
				if (i < paths.length - 1) {
					resolvedPath.append(',');
				}
			}
			velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
			velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
			velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString());
		}
		catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath +
						"] to [java.io.File]: using SpringResourceLoader", ex);
			}
			initSpringResourceLoader(velocityEngine, resourceLoaderPath);
		}
	}
	else {
		// Always load via SpringResourceLoader
		// (without hot detection of template changes).
		if (logger.isDebugEnabled()) {
			logger.debug("File system access not preferred: using SpringResourceLoader");
		}
		initSpringResourceLoader(velocityEngine, resourceLoaderPath);
	}
}