Java Examples for org.springframework.core.io.ResourceLoader
The following java examples will help you to understand the usage of org.springframework.core.io.ResourceLoader. These source code samples are taken from different open source projects.
Example 1
| Project: ProcessPuzzleFramework-master File: ApplicationRepository.java View source code |
//Public mutators
public static ApplicationRepository getInstance(String applicationStoragePath, ResourceLoader resourceLoader) throws InstantiationException {
ApplicationRepository repository = (ApplicationRepository) SingletonRegistry.getInstance(ApplicationRepository.class);
xmlStoragePath = applicationStoragePath;
ApplicationRepository.resourceLoader = resourceLoader;
try {
repository.setStorageXmlPath(applicationStoragePath, resourceLoader);
repository.readXmlDocument();
} catch (DocumentException e) {
throw new InstantiationException("Instantiation of 'ApplicationRepository' caused an error.");
} catch (IOException e) {
throw new InstantiationException("Instantiation of 'ApplicationRepository' caused an error.");
}
return repository;
}Example 2
| Project: javasousuo-master File: ResourceLoaderTest.java View source code |
@Test
public void testResourceLoad() {
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource("classpath:cn/javass/spring/chapter4/test1.txt");
//验�返回的是ClassPathResource
Assert.assertEquals(ClassPathResource.class, resource.getClass());
Resource resource2 = loader.getResource("file:cn/javass/spring/chapter4/test1.txt");
//验�返回的是ClassPathResource
Assert.assertEquals(UrlResource.class, resource2.getClass());
Resource resource3 = loader.getResource("cn/javass/spring/chapter4/test1.txt");
//验è¯?返默认å?¯ä»¥åŠ è½½ClasspathResource
Assert.assertTrue(resource3 instanceof ClassPathResource);
}Example 3
| Project: alien4cloud-master File: FullApplicationConfiguration.java View source code |
@Bean
public static PropertySourcesPlaceholderConfigurer properties(ResourceLoader resourceLoader) {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = AlienYamlPropertiesFactoryBeanFactory.get(resourceLoader);
propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
return propertySourcesPlaceholderConfigurer;
}Example 4
| Project: spring-framework-2.5.x-master File: AbstractApplicationContext.java View source code |
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader.
beanFactory.setBeanClassLoader(getClassLoader());
// Populate the bean factory with context-specific resource editors.
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME) && JdkVersion.isAtLeastJava15()) {
// Register the (JDK 1.5 specific) LoadTimeWeaverAwareProcessor.
try {
Class ltwapClass = ClassUtils.forName("org.springframework.context.weaving.LoadTimeWeaverAwareProcessor", AbstractApplicationContext.class.getClassLoader());
BeanPostProcessor ltwap = (BeanPostProcessor) BeanUtils.instantiateClass(ltwapClass);
((BeanFactoryAware) ltwap).setBeanFactory(beanFactory);
beanFactory.addBeanPostProcessor(ltwap);
} catch (ClassNotFoundException ex) {
throw new IllegalStateException("Spring's LoadTimeWeaverAwareProcessor class is not available");
}
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}Example 5
| Project: spring-modules-master File: FreemarkerTemplateEngine.java View source code |
/**
* Creates a freemarker configuration with the given resource loader, freemarker settings, and shared variables.
*
* @param resourceLoader The resource loader that will be used to load all template resources.
* @param settings The freemarker settings. Can be <code>null</code>
* @param sharedVariables Variables shared by all templates created/managed by this engine.
* @return The created configuration.
* @throws TemplateException thrown when configuration construction fails.
*/
protected static Configuration createConfiguration(ResourceLoader resourceLoader, Properties settings, Map sharedVariables) throws TemplateException {
ResourceLoaderTemplateLoader templateLoader = new ResourceLoaderTemplateLoader(resourceLoader);
Configuration configuration = new Configuration();
configuration.setTemplateLoader(templateLoader);
for (Iterator vars = sharedVariables.entrySet().iterator(); vars.hasNext(); ) {
Map.Entry var = (Map.Entry) vars.next();
configuration.setSharedVariable((String) var.getKey(), var.getValue());
}
if (settings != null) {
configuration.setSettings(settings);
}
return configuration;
}Example 6
| Project: gemini.blueprint-master File: OsgiResourceUtils.java View source code |
/**
* Return the search type to be used for the give string based on the
* prefix.
*
* @param path
* @return
*/
public static int getSearchType(String path) {
Assert.notNull(path);
int type = PREFIX_TYPE_NOT_SPECIFIED;
String prefix = getPrefix(path);
// no prefix is treated just like osgibundle:
if (!StringUtils.hasText(prefix))
type = PREFIX_TYPE_NOT_SPECIFIED;
else if (prefix.startsWith(OsgiBundleResource.BUNDLE_URL_PREFIX))
type = PREFIX_TYPE_BUNDLE_SPACE;
else if (prefix.startsWith(OsgiBundleResource.BUNDLE_JAR_URL_PREFIX))
type = PREFIX_TYPE_BUNDLE_JAR;
else if (prefix.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX))
type = PREFIX_TYPE_CLASS_SPACE;
else if (prefix.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX))
type = PREFIX_TYPE_CLASS_ALL_SPACE;
else
type = PREFIX_TYPE_UNKNOWN;
return type;
}Example 7
| Project: spring-data-commons-master File: RepositoryBeanDefinitionBuilder.java View source code |
/**
* Builds a new {@link BeanDefinitionBuilder} from the given {@link BeanDefinitionRegistry} and {@link ResourceLoader}
* .
*
* @param configuration must not be {@literal null}.
* @return
*/
public BeanDefinitionBuilder build(RepositoryConfiguration<?> configuration) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null!");
Assert.notNull(resourceLoader, "ResourceLoader must not be null!");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(configuration.getRepositoryFactoryBeanClassName());
builder.getRawBeanDefinition().setSource(configuration.getSource());
builder.addConstructorArgValue(configuration.getRepositoryInterface());
builder.addPropertyValue("queryLookupStrategyKey", configuration.getQueryLookupStrategyKey());
builder.addPropertyValue("lazyInit", configuration.isLazyInit());
//
configuration.getRepositoryBaseClassName().ifPresent( it -> builder.addPropertyValue("repositoryBaseClass", it));
NamedQueriesBeanDefinitionBuilder definitionBuilder = new NamedQueriesBeanDefinitionBuilder(extension.getDefaultNamedQueryLocation());
configuration.getNamedQueriesLocation().ifPresent(definitionBuilder::setLocations);
builder.addPropertyValue("namedQueries", definitionBuilder.build(configuration.getSource()));
registerCustomImplementation(configuration).ifPresent( it -> {
builder.addPropertyReference("customImplementation", it);
builder.addDependsOn(it);
});
RootBeanDefinition evaluationContextProviderDefinition = new RootBeanDefinition(ExtensionAwareEvaluationContextProvider.class);
evaluationContextProviderDefinition.setSource(configuration.getSource());
builder.addPropertyValue("evaluationContextProvider", evaluationContextProviderDefinition);
return builder;
}Example 8
| Project: springmvc-mustache-master File: DefaultTemplateLoaderTest.java View source code |
@Test
public void it_should_build_template_loader_using_custom_resource_loader() throws Exception {
DefaultTemplateLoader loader = new DefaultTemplateLoader(resourceLoader);
ResourceLoader resourceLoader = (ResourceLoader) readField(loader, "resourceLoader", true);
String prefix = (String) readField(loader, "prefix", true);
String suffix = (String) readField(loader, "suffix", true);
Map<String, String> partialsAliases = (Map<String, String>) readField(loader, "partialAliases", true);
assertThat(resourceLoader).isNotNull().isSameAs(this.resourceLoader);
assertThat(prefix).isNull();
assertThat(suffix).isNull();
assertThat(partialsAliases).isNotNull().isEmpty();
}Example 9
| Project: blaze-persistence-master File: AbstractEntityViewConfigurationSource.java View source code |
public Collection<BeanDefinition> getCandidates(ResourceLoader resourceLoader) {
EntityViewComponentProvider scanner = new EntityViewComponentProvider(getIncludeFilters());
// scanner.setConsiderNestedRepositoryInterfaces(shouldConsiderNestedRepositories());
scanner.setResourceLoader(resourceLoader);
scanner.setEnvironment(environment);
for (TypeFilter filter : getExcludeFilters()) {
scanner.addExcludeFilter(filter);
}
Set<BeanDefinition> result = new HashSet<BeanDefinition>();
for (String basePackage : getBasePackages()) {
Set<BeanDefinition> candidate = scanner.findCandidateComponents(basePackage);
result.addAll(candidate);
}
return result;
}Example 10
| Project: cas-server-4.0.1-master File: WiringTests.java View source code |
@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 11
| Project: mybatis-plus-master File: MybatisPlusConfig.java View source code |
@Bean("mybatisSqlSession")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, ResourceLoader resourceLoader, GlobalConfiguration globalConfiguration) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
// sqlSessionFactory.setConfigLocation(resourceLoader.getResource("classpath:mybatis-config.xml"));
sqlSessionFactory.setTypeAliasesPackage("com.baomidou.mybatisplus.test.h2.entity.persistent");
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
sqlSessionFactory.setConfiguration(configuration);
PaginationInterceptor pagination = new PaginationInterceptor();
pagination.setDialectType("h2");
sqlSessionFactory.setPlugins(new Interceptor[] { pagination });
sqlSessionFactory.setGlobalConfig(globalConfiguration);
return sqlSessionFactory.getObject();
}Example 12
| Project: spring-boot-master File: SpringApplication.java View source code |
private Banner printBanner(ConfigurableEnvironment environment) {
if (this.bannerMode == Banner.Mode.OFF) {
return null;
}
ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader(getClassLoader());
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
if (this.bannerMode == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
}
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}Example 13
| Project: spring-boot-starter-jade4j-master File: Jade4JTemplateAvailabilityProvider.java View source code |
@Override
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) {
if (ClassUtils.isPresent("de.neuland.jade4j.spring.template.SpringTemplateLoader", classLoader)) {
String prefix = environment.getProperty("spring.jade4j.prefix", Jade4JAutoConfiguration.DEFAULT_PREFIX);
String suffix = environment.getProperty("spring.jade4j.suffix", Jade4JAutoConfiguration.DEFAULT_SUFFIX);
return resourceLoader.getResource(prefix + view + suffix).exists();
}
return false;
}Example 14
| Project: spring-cloud-dataflow-master File: DefaultTaskServiceTests.java View source code |
@Before
public void setupMockMVC() {
taskDefinitionRepository.save(new TaskDefinition(TASK_NAME_ORIG, "demo"));
appRegistry = mock(AppRegistry.class);
resourceLoader = mock(ResourceLoader.class);
metadataResolver = mock(ApplicationConfigurationMetadataResolver.class);
taskLauncher = mock(TaskLauncher.class);
when(this.appRegistry.find(anyString(), any(ApplicationType.class))).thenReturn(new AppRegistration("some-name", task, URI.create("http://helloworld"), resourceLoader));
when(this.resourceLoader.getResource(anyString())).thenReturn(mock(Resource.class));
taskService = new DefaultTaskService(dataSourceProperties, taskDefinitionRepository, taskExplorer, taskExecutionRepository, appRegistry, resourceLoader, taskLauncher, metadataResolver, new TaskConfigurationProperties(), new InMemoryDeploymentIdRepository(), null);
}Example 15
| Project: spring-framework-master File: AbstractApplicationContext.java View source code |
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}Example 16
| Project: trimou-master File: TrimouViewResolverTest.java View source code |
@Test
public void templateResourceInputStreamIsClosed() throws Exception {
final Resource resource = mock(Resource.class);
given(resource.exists()).willReturn(true);
final InputStream inputStream = new ByteArrayInputStream(new byte[0]);
final InputStream spyInputStream = spy(inputStream);
given(resource.getInputStream()).willReturn(spyInputStream);
final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator();
loader.setResourceLoader(new ResourceLoader() {
public Resource getResource(final String location) {
return resource;
}
public ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
});
resolver.setEngine(MustacheEngineBuilder.newBuilder().addTemplateLocator(loader).build());
resolver.loadView("home", null);
verify(spyInputStream).close();
}Example 17
| Project: cas-master File: Beans.java View source code |
/**
* Gets credential selection predicate.
*
* @param selectionCriteria the selection criteria
* @return the credential selection predicate
*/
public static Predicate<org.apereo.cas.authentication.Credential> newCredentialSelectionPredicate(final String selectionCriteria) {
try {
if (StringUtils.isBlank(selectionCriteria)) {
return credential -> true;
}
if (selectionCriteria.endsWith(".groovy")) {
final ResourceLoader loader = new DefaultResourceLoader();
final Resource resource = loader.getResource(selectionCriteria);
if (resource != null) {
final String script = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
final GroovyClassLoader classLoader = new GroovyClassLoader(Beans.class.getClassLoader(), new CompilerConfiguration(), true);
final Class<Predicate> clz = classLoader.parseClass(script);
return clz.newInstance();
}
}
final Class predicateClazz = ClassUtils.getClass(selectionCriteria);
return (Predicate<org.apereo.cas.authentication.Credential>) predicateClazz.newInstance();
} catch (final Exception e) {
final Predicate<String> predicate = Pattern.compile(selectionCriteria).asPredicate();
return credential -> predicate.test(credential.getId());
}
}Example 18
| Project: citrus-master File: AttachmentContent.java View source code |
@Override
protected void render(Part mailPart, String fileName) {
ResourceLoader resourceLoader = containingContent.getResourceLoader();
if (resourceLoader == null) {
throw new MailBuilderException("Could not find resource \"" + resourceName + "\": no resourceLoader specified");
}
Resource resource = resourceLoader.getResource(resourceName);
if (!resource.exists()) {
throw new MailBuilderException("Could not find resource \"" + resourceName + "\"");
}
DataSource ds;
try {
ds = new URLDataSource(resource.getURL());
} catch (IOException e) {
ds = new ResourceDataSource(resource);
}
if (fileName == null) {
fileName = resourceName;
}
render(mailPart, fileName, ds);
}Example 19
| Project: egovframe.rte.3.5-master File: ResultHandlerMapperTest.java View source code |
@Test
public void testResultHandlerForOutFileWriting() throws Exception {
// select to outFile using resultHandler
// 1. DAO방� 테스트
empMapper.selectEmpListToOutFileUsingResultHandler("egovframework.rte.psl.dataaccess.mapper.EmployerMapper.selectEmpListToOutFileUsingResultHandler", resultHandler);
// 2. Mapper방� 테스트
employerMapper.selectEmpListToOutFileUsingResultHandler(resultHandler);
// check
ResourceLoader resourceLoader = new DefaultResourceLoader();
org.springframework.core.io.Resource resource = resourceLoader.getResource("file:./src/test/resources/META-INF/testdata/" + schemaProperties.getProperty("outResultFile"));
// BufferedOutputStream flush ë°? close
// resultHandler.releaseResource();
// ê°? 38,416개씩 ë‘?번 실행했으므로 ì´? 76,832ê°œ ì¶œë ¥
assertEquals(76832, resultHandler.getTotalCount());
File file = resource.getFile();
assertNotNull(file);
// 대용량 out file size 체�
assertTrue(1000000 < file.length());
}Example 20
| Project: egovframework.rte.root-master File: LobTypeTest.java View source code |
public LobTestVO makeVO() throws Exception {
LobTestVO vo = new LobTestVO();
vo.setId(1);
ResourceLoader resourceLoader = new DefaultResourceLoader();
org.springframework.core.io.Resource resource = resourceLoader.getResource("META-INF/testdata/iBATIS-SqlMaps-2_en.pdf");
File file = resource.getFile();
byte[] fileBArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(fileBArray);
vo.setBlobType(fileBArray);
resource = resourceLoader.getResource("META-INF/testdata/index-all.html");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
vo.setClobType(builder.toString());
return vo;
}Example 21
| Project: jbehave-core-master File: SpringApplicationContextFactory.java View source code |
/**
* Creates a configurable application context from the resources provided.
* The context will be an instance of
* {@link AnnotationConfigApplicationContext}, if the resources are
* annotated class names, or {@link GenericApplicationContext} otherwise.
*
* @return A ConfigurableApplicationContext
*/
public ConfigurableApplicationContext createApplicationContext() {
try {
// first try to create annotation config application context
Class<?>[] annotatedClasses = new Class<?>[resources.length];
for (int i = 0; i < resources.length; i++) {
annotatedClasses[i] = this.classLoader.loadClass(resources[i]);
}
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(annotatedClasses);
context.setParent(parent);
context.setClassLoader(classLoader);
return context;
} catch (ClassNotFoundException e) {
GenericApplicationContext context = new GenericApplicationContext(parent);
context.setClassLoader(classLoader);
ResourceLoader resourceLoader = new DefaultResourceLoader(classLoader);
context.setResourceLoader(resourceLoader);
BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
for (String resource : resources) {
reader.loadBeanDefinitions(resourceLoader.getResource(resource));
}
context.refresh();
return context;
}
}Example 22
| Project: jres-master File: PropertyPlaceholderConfigurer.java View source code |
public void setResourceLoader(ResourceLoader resourceLoader) {
String config = System.getProperty(CONFIG_LOCATION);
String[] configs = null;
if (StringUtil.isNotBlank(config)) {
configs = StringUtils.tokenizeToStringArray(config, ",; \t\n");
}
if (configs != null) {
Resource[] resources = new Resource[configs.length];
for (int n = 0; n < resources.length; n++) {
resources[n] = resourceLoader.getResource(configs[n]);
}
super.setLocations(resources);
} else {
super.setLocation(resourceLoader.getResource("classpath:" + System.getProperty(CONFIG_LOCATION)));
}
}Example 23
| Project: jresplus-master File: PropertyPlaceholderConfigurer.java View source code |
public void setResourceLoader(ResourceLoader resourceLoader) {
String config = System.getProperty(CONFIG_LOCATION);
String[] configs = null;
if (StringUtil.isNotBlank(config)) {
configs = StringUtils.tokenizeToStringArray(config, ",; \t\n");
}
if (configs != null) {
Resource[] resources = new Resource[configs.length];
for (int n = 0; n < resources.length; n++) {
resources[n] = resourceLoader.getResource(configs[n]);
}
super.setLocations(resources);
} else {
super.setLocation(resourceLoader.getResource("classpath:" + System.getProperty(CONFIG_LOCATION)));
}
}Example 24
| Project: spring-db4o-master File: ResourceStorageTest.java View source code |
@Test
public void testExists() {
String uri = "resource";
Resource resource = mock(Resource.class);
when(resource.exists()).thenReturn(true);
ResourceLoader resourceLoader = mock(ResourceLoader.class);
when(resourceLoader.getResource(uri)).thenReturn(resource);
ResourceStorage resourceStorage = new ResourceStorage();
resourceStorage.setResourceLoader(resourceLoader);
Assert.assertTrue(resourceStorage.exists(uri));
}Example 25
| Project: spring-security-master File: SecurityMockMvcRequestPostProcessors.java View source code |
/**
* Finds an X509Cetificate using a resoureName and populates it on the request.
*
* @param resourceName the name of the X509Certificate resource
* @return the
* {@link org.springframework.test.web.servlet.request.RequestPostProcessor} to use.
* @throws IOException
* @throws CertificateException
*/
public static RequestPostProcessor x509(String resourceName) throws IOException, CertificateException {
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource(resourceName);
InputStream inputStream = resource.getInputStream();
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(inputStream);
return x509(certificate);
}Example 26
| Project: hdiv-archive-master File: FreeMarkerConfigurerTests.java View source code |
public void testFreemarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws IOException, TemplateException {
FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
fcfb.setTemplateLoaderPath("file:/mydir");
Properties settings = new Properties();
settings.setProperty("localized_lookup", "false");
fcfb.setFreemarkerSettings(settings);
fcfb.setResourceLoader(new ResourceLoader() {
public Resource getResource(String location) {
if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
throw new IllegalArgumentException(location);
}
return new ByteArrayResource("test".getBytes(), "test");
}
public ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
});
fcfb.afterPropertiesSet();
assertTrue(fcfb.getObject() instanceof Configuration);
Configuration fc = (Configuration) fcfb.getObject();
Template ft = fc.getTemplate("test");
assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}Example 27
| Project: jena-sparql-api-master File: MainJavaSparkTest.java View source code |
/**
* Arguments:
* dcat-service=URL url to a dcat dataset index
* dataset=string name of the dataset (will be looked up in the index)
*
*
* @param args
* @throws InterruptedException
* @throws IOException
*/
public static void main(String[] args) throws InterruptedException, IOException {
if (true) {
Object o = 1;
//Node n = NodeFactory.createLiteralByValue(o, TypeMapper.getInstance().getTypeByValue(o));
Node n = NodeFactory.createURI("http://test");
String s = FmtUtils.stringForNode(n);
System.out.println(s);
Node m = RiotLib.parse(s);
System.out.println(m);
System.exit(0);
}
if (args.length < 1) {
logger.error("=> wrong parameters number");
System.err.println("Usage: FileName <path-to-files> <output-path>");
System.exit(1);
}
String fileName = args[0];
String sparkMasterHost = args.length >= 2 ? args[1] : "local[2]";
// Option<String> tmp = SparkContext.jarOfClass(MainJavaSparkTest.class);
// String jar = tmp.get();
// logger.info("Jar: " + jar);
SparkConf sparkConf = new SparkConf().setAppName("BDE-readRDF").setMaster(sparkMasterHost).set(//.set("spark.local.ip", "localhost") //"139.18.8.88")
"spark.serializer", "org.apache.spark.serializer.KryoSerializer").set("spark.sql.autoBroadcastJoinThreshold", "300000000");
String dataset = "training-dataset";
Path rddCachePath = FileSystems.getDefault().getPath("target");
File fwdRddCacheFileTmp = rddCachePath.resolve(dataset + "-fwd.ser").toFile();
File bwdRddCacheFileTmp = rddCachePath.resolve(dataset + "-bwd.ser").toFile();
String fwdRddPath = fwdRddCacheFileTmp.getAbsolutePath();
String bwdRddPath = bwdRddCacheFileTmp.getAbsolutePath();
System.out.println("Cache paths: " + fwdRddPath + " - " + bwdRddPath);
JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);
Partitioner nodePartitioner = new HashPartitioner(10);
Stopwatch sw = Stopwatch.createStarted();
JavaPairRDD<Node, Tuple2<Node, Node>> tmpFwdRdd;
if (fwdRddCacheFileTmp.exists()) {
//JavaRDD<Tuple2<Node, Tuple2<Node, Node>>> tmp = sparkContext.objectFile(fwdRddPath);
//TypeToken<Tuple2<Node, Node>> typeToken = new TypeToken<Tuple2<Node, Node>>() {};
//fwdRdd = (JavaPairRDD<Node, Tuple2<Node, Node>>) sparkContext.sequenceFile(fwdRddPath, Node.class, typeToken.getRawType());
//fwdRdd = tmp.mapToPair(f)//new JavaPairRDD<Node, Tuple2<Node, Node>>(tmp.rdd());
tmpFwdRdd = sparkContext.objectFile(fwdRddPath).mapToPair(new PairFunction<Object, Node, Tuple2<Node, Node>>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<Node, Tuple2<Node, Node>> call(Object t) throws Exception {
return (Tuple2<Node, Tuple2<Node, Node>>) t;
}
});
} else {
tmpFwdRdd = sparkContext.textFile(fileName, 5).filter(//.parallelize(triples)
line -> !line.trim().isEmpty() & !line.startsWith("#")).map( line -> {
Triple r;
try {
r = RDFDataMgr.createIteratorTriples(new ByteArrayInputStream(line.getBytes()), Lang.NTRIPLES, "http://example/base").next();
} catch (Exception e) {
logger.warn("Errornous line: " + line, e);
r = null;
}
return r;
}).filter(new org.apache.spark.api.java.function.Function<Triple, Boolean>() {
private static final long serialVersionUID = 1;
@Override
public Boolean call(Triple t) throws Exception {
return t != null;
}
}).mapToPair(new PairFunction<Triple, Node, Tuple2<Node, Node>>() {
private static final long serialVersionUID = -4757627441301230743L;
@Override
public Tuple2<Node, Tuple2<Node, Node>> call(Triple t) throws Exception {
return new Tuple2<>(t.getSubject(), new Tuple2<>(t.getPredicate(), t.getObject()));
}
});
//fwdRdd.saveAsObjectFile(fwdRddCacheFileTmp.getAbsolutePath());
}
JavaPairRDD<Node, Tuple2<Node, Node>> fwdRdd = tmpFwdRdd.partitionBy(nodePartitioner).persist(StorageLevel.MEMORY_AND_DISK_SER());
fwdRdd.count();
System.out.println("Loaded FWD RDD:" + sw.elapsed(TimeUnit.SECONDS));
JavaPairRDD<Node, Tuple2<Node, Node>> tmpBwdRdd;
if (bwdRddCacheFileTmp.exists()) {
tmpBwdRdd = sparkContext.objectFile(bwdRddPath).mapToPair(new PairFunction<Object, Node, Tuple2<Node, Node>>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<Node, Tuple2<Node, Node>> call(Object t) throws Exception {
return (Tuple2<Node, Tuple2<Node, Node>>) t;
}
});
} else {
tmpBwdRdd = tmpFwdRdd.mapToPair(new PairFunction<Tuple2<Node, Tuple2<Node, Node>>, Node, Tuple2<Node, Node>>() {
private static final long serialVersionUID = -1567531441301230743L;
@Override
public Tuple2<Node, Tuple2<Node, Node>> call(Tuple2<Node, Tuple2<Node, Node>> t) throws Exception {
return new Tuple2<>(t._2._2, new Tuple2<>(t._2._1, t._1));
}
});
//bwdRdd.saveAsObjectFile(bwdRddPath);;
}
JavaPairRDD<Node, Tuple2<Node, Node>> bwdRdd = tmpBwdRdd.partitionBy(nodePartitioner).persist(StorageLevel.MEMORY_AND_DISK_SER());
bwdRdd.count();
System.out.println("Loaded BWD RDD:" + sw.elapsed(TimeUnit.SECONDS));
sw.stop();
ResourceLoader resourceLoader = new AnnotationConfigApplicationContext();
Model datasetModel = ModelFactory.createDefaultModel();
QueryExecutionFactory dcatQef = FluentQueryExecutionFactory.model(datasetModel).create();
SparqlPathUtils.readModel(datasetModel, resourceLoader, "classpath:dcat-eswc-training.ttl", Lang.TURTLE);
PrefixMappingImpl pm = new PrefixMappingImpl();
pm.setNsPrefix("jsafn", "http://jsa.aksw.org/fn/");
pm.setNsPrefixes(PrefixMapping.Extended);
Prologue prologue = new Prologue(pm);
SparqlStmtParserImpl sparqlStmtParser = SparqlStmtParserImpl.create(SparqlParserConfig.create(Syntax.syntaxARQ, prologue));
SparqlServiceFactory ssf = new SparqlServiceFactory() {
@Override
public SparqlService createSparqlService(String serviceUri, DatasetDescription datasetDescription, HttpClient httpClient) {
SparqlService coreSparqlService = FluentSparqlService.http(serviceUri, datasetDescription, httpClient).create();
SparqlService r = MainSparqlPath2.proxySparqlService(coreSparqlService, sparqlStmtParser, prologue);
return r;
}
};
ssf = FluentSparqlServiceFactory.from(ssf).configFactory().defaultServiceUri(//.defaultServiceUri("http://dbpedia.org/sparql")
"http://localhost:8890/sparql").configService().configQuery().end().end().end().create();
PropertyFunctionRegistry.get().put(PropertyFunctionKShortestPaths.DEFAULT_IRI, new PropertyFunctionFactoryKShortestPaths( sps -> new SparqlKShortestPathFinderSpark(sparkContext, fwdRdd, bwdRdd)));
Server server = SparqlServerUtils.startSparqlEndpoint(ssf, sparqlStmtParser, 7533);
server.join();
sparkContext.close();
}Example 28
| Project: lesscss-compile-service-master File: MappedSpringLessControllerTest.java View source code |
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
controller = new MappedSpringLessController();
compileService = mock(LessCompileService.class);
resourceLoader = mock(ResourceLoader.class);
resource = mock(Resource.class);
controller.setCompileService(compileService);
controller.setResourceLoader(resourceLoader);
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}Example 29
| Project: mateo-master File: GenericWebXmlContextLoader.java View source code |
private MockServletContext initServletContext(String warRootDir, ResourceLoader resourceLoader) {
return new MockServletContext(warRootDir, resourceLoader) {
// Required for DefaultServletHttpRequestHandler...
@Override
public RequestDispatcher getNamedDispatcher(String path) {
return (path.equals("default")) ? new MockRequestDispatcher(path) : super.getNamedDispatcher(path);
}
};
}Example 30
| Project: solarnetwork-common-master File: PatternMatchingResourceBundleMessagesSource.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
super.setResourceLoader(resourceLoader);
if (resourceResolver == null) {
if (resourceLoader instanceof ResourcePatternResolver) {
resourceResolver = (ResourcePatternResolver) resourceLoader;
} else {
resourceResolver = new PathMatchingResourcePatternResolver(resourceLoader);
}
}
}Example 31
| Project: spring-cloud-aws-master File: ContextResourceLoaderBeanDefinitionParserTest.java View source code |
@Test
public void parseInternal_defaultConfiguration_createsAmazonS3ClientWithoutRegionConfigured() throws Exception {
//Arrange
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
//Act
ResourceLoader resourceLoader = applicationContext.getBean(ResourceLoaderBean.class).getResourceLoader();
//Assert
assertTrue(PathMatchingSimpleStorageResourcePatternResolver.class.isInstance(resourceLoader));
}Example 32
| Project: spring-data-gemfire-master File: GemfireRepositoryConfigurationExtensionTest.java View source code |
protected XmlReaderContext mockXmlReaderContext() {
ResourceLoader mockResourceLoader = mock(ResourceLoader.class);
XmlBeanDefinitionReader mockXmlBeanDefinitionReader = mock(XmlBeanDefinitionReader.class);
when(mockResourceLoader.getClassLoader()).thenReturn(Thread.currentThread().getContextClassLoader());
when(mockXmlBeanDefinitionReader.getResourceLoader()).thenReturn(mockResourceLoader);
return new XmlReaderContext(null, null, null, new PassThroughSourceExtractor(), mockXmlBeanDefinitionReader, null);
}Example 33
| Project: spring-portlet-contrib-master File: GenericPortletFilterBean.java View source code |
@Override
public void init(FilterConfig filterConfig) throws PortletException {
Assert.notNull(filterConfig, "FilterConfig must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Initializing filter '" + filterConfig.getFilterName() + "'");
}
this.filterConfig = filterConfig;
// Set bean properties from init parameters.
try {
PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new PortletContextResourceLoader(filterConfig.getPortletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.environment));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
} catch (BeansException ex) {
String msg = "Failed to set bean properties on filter '" + filterConfig.getFilterName() + "': " + ex.getMessage();
logger.error(msg, ex);
throw new PortletException(msg, ex);
}
// Let subclasses do whatever initialization they like.
initFilterBean();
if (logger.isDebugEnabled()) {
logger.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully");
}
}Example 34
| Project: spring-test-dbunit-master File: AbstractDataSetLoader.java View source code |
/**
* Loads a {@link IDataSet dataset} from {@link Resource}s obtained from the specified <tt>location</tt>. Each
* <tt>location</tt> can be mapped to a number of potential {@link #getResourceLocations resources}, the first
* resource that {@link Resource#exists() exists} will be used. {@link Resource}s are loaded using the
* {@link ResourceLoader} returned from {@link #getResourceLoader}.
* <p>
* If no resource can be found then <tt>null</tt> will be returned.
*
* @see #createDataSet(Resource)
* @see com.github.springtestdbunit.dataset.DataSetLoader#loadDataSet(Class, String) java.lang.String)
*/
public IDataSet loadDataSet(Class<?> testClass, String location) throws Exception {
ResourceLoader resourceLoader = getResourceLoader(testClass);
String[] resourceLocations = getResourceLocations(testClass, location);
for (String resourceLocation : resourceLocations) {
Resource resource = resourceLoader.getResource(resourceLocation);
if (resource.exists()) {
return createDataSet(resource);
}
}
return null;
}Example 35
| Project: uaa-master File: IntegrationTestContextLoader.java View source code |
protected void configureWebResources(AnnotationConfigWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {
ApplicationContext parent = context.getParent();
// the Root WAC:
if (parent == null || (!(parent instanceof WebApplicationContext))) {
String resourceBasePath = webMergedConfig.getResourceBasePath();
ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() : new FileSystemResourceLoader();
ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
context.setServletContext(servletContext);
} else {
ServletContext servletContext = null;
// find the Root WAC
while (parent != null) {
if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
servletContext = ((WebApplicationContext) parent).getServletContext();
break;
}
parent = parent.getParent();
}
Assert.state(servletContext != null, "Failed to find Root WebApplicationContext in the context hierarchy");
context.setServletContext(servletContext);
}
}Example 36
| Project: citrus-sample-master File: StoreManagerImpl.java View source code |
public void afterPropertiesSet() {
try {
uploadDir = resourceLoader.getResource(UPLOAD_DIR).getFile();
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
if (!uploadDir.isDirectory()) {
throw new IOException("Could not create directory " + uploadDir.getAbsolutePath());
}
} catch (Exception e) {
throw new StoreManagerException("Could not get upload directory from ResourceLoader: " + UPLOAD_DIR);
}
}Example 37
| Project: jasypt-spring-boot-master File: EncryptablePropertySourceBeanFactoryPostProcessor.java View source code |
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
ResourceLoader ac = new DefaultResourceLoader();
EncryptablePropertyResolver resolver = beanFactory.getBean(env.resolveRequiredPlaceholders(RESOLVER_BEAN_PLACEHOLDER), EncryptablePropertyResolver.class);
MutablePropertySources propertySources = env.getPropertySources();
Stream<AnnotationAttributes> encryptablePropertySourcesMetadata = getEncryptablePropertySourcesMetadata(beanFactory);
encryptablePropertySourcesMetadata.forEach( eps -> loadEncryptablePropertySource(eps, env, ac, resolver, propertySources));
}Example 38
| Project: liferay-portal-master File: PortalClientBuilder.java View source code |
private HttpServlet _createAxisHttpServlet(final File docRootDir) throws ServletException {
AxisServlet axisServlet = new AxisServlet();
MockServletConfig mockServletConfig = new MockServletConfig(new MockServletContext(new ResourceLoader() {
@Override
public ClassLoader getClassLoader() {
return AxisServlet.class.getClassLoader();
}
@Override
public Resource getResource(String name) {
return new FileSystemResource(new File(docRootDir, name));
}
}), "Axis Servlet");
axisServlet.init(mockServletConfig);
return axisServlet;
}Example 39
| Project: mapfish-print-master File: MapfishJsonFileResolverTest.java View source code |
@Test
public void testLoadFromServlet() throws Throwable {
final File rootFile = getFile("/test-http-request-factory-application-context.xml").getParentFile();
configFileLoader.setServletContext(new MockServletContext(new ResourceLoader() {
@Override
public Resource getResource(String location) {
final File file = new File(rootFile, location);
if (file.exists()) {
return new FileSystemResource(file);
}
throw new IllegalArgumentException(file + " not found");
}
@Override
public ClassLoader getClassLoader() {
return MapfishJsonFileResolverTest.class.getClassLoader();
}
}));
final String configFile = "/org/mapfish/print/map/style/json/requestData-style-json-v1-style.json";
final String styleString = "servlet:///org/mapfish/print/map/style/json/v2-style-symbolizers-default-values.json";
final Optional<Style> styleOptional = loadStyle(configFile, styleString);
assertTrue(styleOptional.isPresent());
assertNotNull(styleOptional.get());
}Example 40
| Project: sagan-master File: SearchResultParser_WithoutHighlightTests.java View source code |
@Test
public void useSourceSummary() {
assertThat(content.get(0).getSummary(), equalTo("org.springframework.context Interface ApplicationContext All Superinterfaces: ApplicationEventPublisher, BeanFactory, EnvironmentCapable, HierarchicalBeanFactory, ListableBeanFactory, MessageSource, ResourceLoader, ResourcePatternResolver All Known Subinterfaces: ConfigurableApplicationContext, ConfigurablePortletApplicationContext, ConfigurableWebApplicationContext, WebApplicationContext All Known Implementing Classes: AbstractApplicationContext, AbstractRefreshableApplicationContext, AbstractR"));
}Example 41
| Project: spring-data-jpa-master File: ClasspathScanningPersistenceUnitPostProcessorUnitTests.java View source code |
// DATAJPA-519
@Test
public void shouldFindJpaMappingFilesFromNestedJarLocationsOnClasspath() {
String nestedModule3Path = "org/springframework/data/jpa/support/module3/module3-orm.xml";
final String fileInJarUrl = "jar:file:/foo/bar/lib/somelib.jar!/" + nestedModule3Path;
ResourceLoader resolver = new PathMatchingResourcePatternResolver(new DefaultResourceLoader()) {
public Resource[] getResources(String locationPattern) throws IOException {
Resource[] resources = super.getResources(locationPattern);
resources = Arrays.copyOf(resources, resources.length + 1);
resources[resources.length - 1] = new UrlResource(fileInJarUrl);
return resources;
}
@Override
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, URL rootUri, String subPattern) throws IOException {
if (fileInJarUrl.equals(rootUri.toString())) {
return Collections.singleton(rootDirResource);
}
return super.doFindPathMatchingJarResources(rootDirResource, rootUri, subPattern);
}
};
ClasspathScanningPersistenceUnitPostProcessor processor = new ClasspathScanningPersistenceUnitPostProcessor(basePackage);
ReflectionTestUtils.setField(processor, "mappingFileResolver", resolver);
processor.setMappingFileNamePattern("**/*orm.xml");
processor.postProcessPersistenceUnitInfo(pui);
verify(pui).addMappingFileName("org/springframework/data/jpa/support/module1/module1-orm.xml");
verify(pui).addMappingFileName("org/springframework/data/jpa/support/module2/module2-orm.xml");
verify(pui).addMappingFileName(nestedModule3Path);
}Example 42
| Project: wro4j-tag-master File: Wro4jTagTest.java View source code |
@Before
public void mockContainer() {
final ResourceLoader resourceLoader = createMock(ResourceLoader.class);
expect(resourceLoader.getResource("/WEB-INF/wro.xml")).andAnswer(new IAnswer<Resource>() {
@Override
public Resource answer() throws Throwable {
return new UrlResource(Wro4jTagTest.class.getClassLoader().getResource("config/wro.xml"));
}
}).anyTimes();
replay(resourceLoader);
MockServletContext mockServletContext = new MockServletContext(resourceLoader);
mockPageContext = new MockPageContext(mockServletContext);
}Example 43
| Project: opennms_dashboard-master File: JUnitSnmpAgentExecutionListener.java View source code |
private void handleSnmpAgent(final TestContext testContext, final JUnitSnmpAgent config, MockSnmpDataProvider provider) throws IOException, UnknownHostException, InterruptedException {
if (config == null)
return;
String factoryClassName = "unknown";
try {
final SnmpAgentConfigFactory factory = testContext.getApplicationContext().getBean("snmpPeerFactory", SnmpAgentConfigFactory.class);
factoryClassName = factory.getClass().getName();
} catch (final Throwable t) {
}
if (!factoryClassName.contains("ProxySnmpAgentConfigFactory")) {
LogUtils.warnf(this, "SNMP Peer Factory (%s) is not the ProxySnmpAgentConfigFactory -- did you forget to include applicationContext-proxy-snmp.xml?", factoryClassName);
}
final String useMockSnmpStrategy = System.getProperty(USE_STRATEGY_PROPERTY, useMockSnmpStrategyDefault.toString());
LogUtils.debugf(this, "handleSnmpAgent(testContext, %s, %s)", config, useMockSnmpStrategy);
String host = config.host();
if (host == null || "".equals(host)) {
/*
* NOTE: This call produces different results on different platforms so make
* sure your client code is aware of this. If you use the {@link ProxySnmpAgentConfigFactory}
* by including the <code>classpath:/META-INF/opennms/applicationContext-proxy-snmp.xml</code>
* Spring context, you probably won't need to deal with this. It will override the
* SnmpPeerFactory with the correct values.
*
* Linux: 127.0.0.1
* Mac OS: primary external interface
*/
host = InetAddressUtils.getLocalHostAddressAsString();
//host = "127.0.0.1";
}
final ResourceLoader loader = new DefaultResourceLoader();
final Resource resource = loader.getResource(config.resource());
// NOTE: The default value for config.port is specified inside {@link JUnitSnmpAgent}
final InetAddress hostAddress = addr(host);
final int port = config.port();
final SnmpAgentAddress agentAddress = new SnmpAgentAddress(hostAddress, port);
final InetAddress localHost = InetAddress.getLocalHost();
final SnmpAgentConfigProxyMapper mapper = SnmpAgentConfigProxyMapper.getInstance();
SnmpAgentAddress listenAddress = null;
// try to find an unused port on localhost
int mappedPort = 1161;
do {
listenAddress = new SnmpAgentAddress(localHost, mappedPort++);
} while (mapper.contains(listenAddress));
if (Boolean.valueOf(useMockSnmpStrategy)) {
// map to itself =)
mapper.addProxy(hostAddress, agentAddress);
} else {
MockSnmpAgent agent = null;
while (agent == null) {
try {
agent = MockSnmpAgent.createAgentAndRun(resource.getURL(), str(listenAddress.getAddress()) + "/" + listenAddress.getPort());
break;
} catch (final InterruptedException e) {
if (e.getCause() instanceof BindException && e.getCause().getMessage().contains("already in use")) {
do {
listenAddress = new SnmpAgentAddress(localHost, mappedPort++);
} while (mapper.contains(listenAddress));
} else {
throw e;
}
}
}
mapper.addProxy(hostAddress, listenAddress);
LogUtils.debugf(this, "using MockSnmpAgent on %s for 'real' address %s", listenAddress, agentAddress);
@SuppressWarnings("unchecked") final Map<SnmpAgentAddress, MockSnmpAgent> agents = (Map<SnmpAgentAddress, MockSnmpAgent>) testContext.getAttribute(AGENT_KEY);
agents.put(agentAddress, agent);
}
provider.setDataForAddress(agentAddress, resource);
}Example 44
| Project: cms-ce-master File: SitePropertiesServiceTest.java View source code |
private Resource getLocalTestSitePropertyResouce() {
ResourceLoader testResourceLoader = new FileSystemResourceLoader();
Resource testResource = testResourceLoader.getResource("classpath:com/enonic/cms/core/test.site.properties");
if (!testResource.exists()) {
fail("Could not load test resource: " + testResource);
}
return testResource;
}Example 45
| Project: com.revolsys.open-master File: ModuleImport.java View source code |
protected GenericApplicationContext getApplicationContext(final BeanDefinitionRegistry parentRegistry) {
if (this.applicationContext == null) {
this.applicationContext = new GenericApplicationContext();
if (parentRegistry instanceof ResourceLoader) {
final ResourceLoader resourceLoader = (ResourceLoader) parentRegistry;
final ClassLoader classLoader = resourceLoader.getClassLoader();
this.applicationContext.setClassLoader(classLoader);
}
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.applicationContext, null);
final DefaultListableBeanFactory beanFactory = this.applicationContext.getDefaultListableBeanFactory();
final BeanFactory parentBeanFactory = (BeanFactory) parentRegistry;
for (final String beanName : parentRegistry.getBeanDefinitionNames()) {
final BeanDefinition beanDefinition = parentRegistry.getBeanDefinition(beanName);
final String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null) {
if (beanClassName.equals(AttributeMap.class.getName())) {
registerTargetBeanDefinition(this.applicationContext, parentBeanFactory, beanName, beanName);
this.beanNamesNotToExport.add(beanName);
} else if (beanClassName.equals(MapFactoryBean.class.getName())) {
final PropertyValue targetMapClass = beanDefinition.getPropertyValues().getPropertyValue("targetMapClass");
if (targetMapClass != null) {
final Object mapClass = targetMapClass.getValue();
if (AttributeMap.class.getName().equals(mapClass)) {
registerTargetBeanDefinition(this.applicationContext, parentBeanFactory, beanName, beanName);
this.beanNamesNotToExport.add(beanName);
}
}
}
}
}
beanFactory.addPropertyEditorRegistrar(this.resourceEditorRegistrar);
final AttributesBeanConfigurer attributesConfig = new AttributesBeanConfigurer(this.applicationContext, this.parameters);
this.applicationContext.addBeanFactoryPostProcessor(attributesConfig);
for (final String beanName : this.importBeanNames) {
registerTargetBeanDefinition(this.applicationContext, parentBeanFactory, beanName, beanName);
this.beanNamesNotToExport.add(beanName);
}
for (final Entry<String, String> entry : this.importBeanAliases.entrySet()) {
final String beanName = entry.getKey();
final String aliasName = entry.getValue();
registerTargetBeanDefinition(this.applicationContext, parentBeanFactory, beanName, aliasName);
this.beanNamesNotToExport.add(aliasName);
}
final XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(this.applicationContext);
for (final Resource resource : this.resources) {
beanReader.loadBeanDefinitions(resource);
}
this.applicationContext.refresh();
}
return this.applicationContext;
}Example 46
| Project: genie-master File: SAMLConfigUnitTests.java View source code |
private SAMLProperties setupForKeyManager() {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
this.config.setResourceLoader(resourceLoader);
final Resource storeFile = Mockito.mock(Resource.class);
final SAMLProperties properties = Mockito.mock(SAMLProperties.class);
this.config.setSamlProperties(properties);
final String keyStorePassword = UUID.randomUUID().toString();
final String keyStoreName = UUID.randomUUID().toString() + ".jks";
final String defaultKeyName = UUID.randomUUID().toString();
final String defaultKeyPassword = UUID.randomUUID().toString();
final SAMLProperties.Keystore keyStore = Mockito.mock(SAMLProperties.Keystore.class);
final SAMLProperties.Keystore.DefaultKey defaultKey = Mockito.mock(SAMLProperties.Keystore.DefaultKey.class);
Mockito.when(properties.getKeystore()).thenReturn(keyStore);
Mockito.when(keyStore.getName()).thenReturn(keyStoreName);
Mockito.when(keyStore.getPassword()).thenReturn(keyStorePassword);
Mockito.when(keyStore.getDefaultKey()).thenReturn(defaultKey);
Mockito.when(defaultKey.getName()).thenReturn(defaultKeyName);
Mockito.when(defaultKey.getPassword()).thenReturn(defaultKeyPassword);
Mockito.when(resourceLoader.getResource(Mockito.eq("classpath:" + keyStoreName))).thenReturn(storeFile);
return properties;
}Example 47
| Project: grails-core-master File: ReloadableResourceBundleMessageSource.java View source code |
protected Resource locateResourceWithoutCache(String filename) {
Resource resource = resourceLoader.getResource(org.grails.io.support.ResourceLoader.CLASSPATH_URL_PREFIX + filename + PROPERTIES_SUFFIX);
if (!resource.exists()) {
resource = resourceLoader.getResource(filename + PROPERTIES_SUFFIX);
}
if (!resource.exists()) {
resource = resourceLoader.getResource(filename + XML_SUFFIX);
}
if (resource.exists()) {
return resource;
} else {
return null;
}
}Example 48
| Project: grails-master File: ReloadableResourceBundleMessageSource.java View source code |
protected Resource locateResourceWithoutCache(String filename) {
Resource resource = resourceLoader.getResource(org.grails.io.support.ResourceLoader.CLASSPATH_URL_PREFIX + filename + PROPERTIES_SUFFIX);
if (!resource.exists()) {
resource = resourceLoader.getResource(filename + PROPERTIES_SUFFIX);
}
if (!resource.exists()) {
resource = resourceLoader.getResource(filename + XML_SUFFIX);
}
if (resource.exists()) {
return resource;
} else {
return null;
}
}Example 49
| Project: Katari-master File: ConditionalImportParser.java View source code |
/**
* Parses the and register bean.
*
* @param element
* the element
* @param parserContext
* the parser context
*
* @return the bean definition
*/
private BeanDefinition parseAndRegisterBean(final Element element, final ParserContext parserContext) {
XmlBeanDefinitionReader beanReader;
beanReader = new XmlBeanDefinitionReader(parserContext.getRegistry());
// Configure the bean definition reader with this context's
// resource loading environment.
ResourceLoader resourceLoader;
resourceLoader = parserContext.getReaderContext().getResourceLoader();
beanReader.setResourceLoader(resourceLoader);
beanReader.setEntityResolver(new ResourceEntityResolver(resourceLoader));
String location = element.getAttribute(MODULE);
location = location.replaceAll("\\.", "/");
location = CLASSPATH_PREFIX.concat(location).concat("/").concat(KATARI_MODULE_NAME);
beanReader.loadBeanDefinitions(location);
return null;
}Example 50
| Project: light-admin-master File: LightAdminBeanDefinitionRegistryPostProcessor.java View source code |
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
WebApplicationContext rootContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
EntityManager entityManager = findEntityManager(rootContext);
ResourceLoader resourceLoader = newResourceLoader(servletContext);
Set<Class> administrationConfigs = scanPackageForAdministrationClasses();
Set<ConfigurationUnits> configurationUnits = configurationUnits(rootContext, administrationConfigs);
registry.registerBeanDefinition(JPA_MAPPPING_CONTEXT_BEAN, mappingContext(entityManager));
registry.registerBeanDefinition(CONFIGURATION_UNITS_VALIDATOR_BEAN, configurationUnitsValidator(resourceLoader));
for (Class<?> managedEntityType : managedEntities(entityManager)) {
Class repoInterface = createDynamicRepositoryClass(managedEntityType, entityManager);
registry.registerBeanDefinition(beanName(repoInterface), repositoryFactory(repoInterface, entityManager));
}
registerRepositoryEventListeners(configurationUnits, registry);
registry.registerBeanDefinition(beanName(GlobalAdministrationConfiguration.class), globalAdministrationConfigurationFactoryBeanDefinition(configurationUnits));
registry.registerBeanDefinition(beanName(DomainTypeAdministrationConfigurationFactory.class), domainTypeAdministrationConfigurationFactoryDefinition(entityManager));
}Example 51
| Project: OpenConext-teams-master File: Application.java View source code |
@Autowired
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(Environment environment, PersonRepository personRepository, @Value("${teamsURL}") String teamsURL, @Value("${displayExternalTeams}") Boolean displayExternalTeams, @Value("${displayExternalTeamMembers}") Boolean displayExternalTeamMembers, @Value("${displayAddExternalGroupToTeam}") Boolean displayAddExternalGroupToTeam, @Value("${application.version}") String applicationVersion, @Value("${voot.api.user}") String vootApiUser, @Value("${voot.api.password}") String vootApiPassword, ResourceLoader resourceLoader) throws Exception {
List<HandlerInterceptor> interceptors = new ArrayList<>();
String commitId = gitCommitId(resourceLoader, environment);
interceptors.add(new FeatureInterceptor(displayExternalTeams, displayExternalTeamMembers, displayAddExternalGroupToTeam, commitId, applicationVersion));
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
interceptors.add(localeChangeInterceptor);
if (environment.acceptsProfiles(DEV_PROFILE_NAME)) {
LOG.debug("Using mock shibboleth");
interceptors.add(new MockLoginInterceptor(teamsURL, personRepository));
} else {
interceptors.add(new LoginInterceptor(teamsURL, personRepository));
}
interceptors.add(new VootApiSecurityFilter(vootApiUser, vootApiPassword));
return new SpringMvcConfiguration(interceptors);
}Example 52
| Project: spring-batch-master File: ConcurrentTransactionTests.java View source code |
/**
* This datasource configuration configures the HSQLDB instance using MVCC. When
* configurd using the default behavior, transaction serialization errors are
* thrown (default configuration example below).
*
* return new PooledEmbeddedDataSource(new EmbeddedDatabaseBuilder().
* addScript("classpath:org/springframework/batch/core/schema-drop-hsqldb.sql").
* addScript("classpath:org/springframework/batch/core/schema-hsqldb.sql").
* build());
* @return
*/
@Bean
DataSource dataSource() {
ResourceLoader defaultResourceLoader = new DefaultResourceLoader();
EmbeddedDatabaseFactory embeddedDatabaseFactory = new EmbeddedDatabaseFactory();
embeddedDatabaseFactory.setDatabaseConfigurer(new EmbeddedDatabaseConfigurer() {
@Override
public void configureConnectionProperties(ConnectionProperties properties, String databaseName) {
try {
properties.setDriverClass((Class<? extends Driver>) ClassUtils.forName("org.hsqldb.jdbcDriver", this.getClass().getClassLoader()));
} catch (Exception e) {
e.printStackTrace();
}
properties.setUrl("jdbc:hsqldb:mem:" + databaseName + ";hsqldb.tx=mvcc");
properties.setUsername("sa");
properties.setPassword("");
}
@Override
public void shutdown(DataSource dataSource, String databaseName) {
try {
Connection connection = dataSource.getConnection();
Statement stmt = connection.createStatement();
stmt.execute("SHUTDOWN");
} catch (SQLException ex) {
}
}
});
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(defaultResourceLoader.getResource("classpath:org/springframework/batch/core/schema-drop-hsqldb.sql"));
databasePopulator.addScript(defaultResourceLoader.getResource("classpath:org/springframework/batch/core/schema-hsqldb.sql"));
embeddedDatabaseFactory.setDatabasePopulator(databasePopulator);
return embeddedDatabaseFactory.getDatabase();
}Example 53
| Project: spring-cloud-netflix-master File: EurekaServerAutoConfiguration.java View source code |
/**
* Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources
* required by the Eureka server.
*/
@Bean
public javax.ws.rs.core.Application jerseyApplication(Environment environment, ResourceLoader resourceLoader) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false, environment);
// Filter to include only classes that have a particular annotation.
//
provider.addIncludeFilter(new AnnotationTypeFilter(Path.class));
provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class));
// Find classes in Eureka packages (or subpackages)
//
Set<Class<?>> classes = new HashSet<Class<?>>();
for (String basePackage : EUREKA_PACKAGES) {
Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
for (BeanDefinition bd : beans) {
Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(), resourceLoader.getClassLoader());
classes.add(cls);
}
}
// Construct the Jersey ResourceConfig
//
Map<String, Object> propsAndFeatures = new HashMap<String, Object>();
propsAndFeatures.put(// Skip static content used by the webapp
ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*");
DefaultResourceConfig rc = new DefaultResourceConfig(classes);
rc.setPropertiesAndFeatures(propsAndFeatures);
return rc;
}Example 54
| Project: spring-cloud-stream-modules-master File: JdbcSinkConfiguration.java View source code |
@ConditionalOnProperty("initialize")
@Bean
public DataSourceInitializer nonBootDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource);
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.setIgnoreFailedDrops(true);
dataSourceInitializer.setDatabasePopulator(databasePopulator);
if ("true".equals(properties.getInitialize())) {
databasePopulator.addScript(new DefaultInitializationScriptResource(properties));
} else {
databasePopulator.addScript(resourceLoader.getResource(properties.getInitialize()));
}
return dataSourceInitializer;
}Example 55
| Project: spring-integration-master File: IntegrationComponentScanRegistrar.java View source code |
private static void invokeAwareMethods(Object parserStrategyBean, Environment environment, ResourceLoader resourceLoader, BeanDefinitionRegistry registry) {
if (parserStrategyBean instanceof Aware) {
if (parserStrategyBean instanceof BeanClassLoaderAware) {
ClassLoader classLoader = (registry instanceof ConfigurableBeanFactory ? ((ConfigurableBeanFactory) registry).getBeanClassLoader() : resourceLoader.getClassLoader());
((BeanClassLoaderAware) parserStrategyBean).setBeanClassLoader(classLoader);
}
if (parserStrategyBean instanceof BeanFactoryAware && registry instanceof BeanFactory) {
((BeanFactoryAware) parserStrategyBean).setBeanFactory((BeanFactory) registry);
}
if (parserStrategyBean instanceof EnvironmentAware) {
((EnvironmentAware) parserStrategyBean).setEnvironment(environment);
}
if (parserStrategyBean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) parserStrategyBean).setResourceLoader(resourceLoader);
}
}
}Example 56
| Project: spring-ws-master File: CommonsXsdSchemaCollection.java View source code |
@Override
public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) {
if (resourceLoader != null) {
Resource resource = resourceLoader.getResource(schemaLocation);
if (resource.exists()) {
return createInputSource(resource);
} else if (StringUtils.hasLength(baseUri)) {
// let's try and find it relative to the baseUri, see SWS-413
try {
Resource baseUriResource = new UrlResource(baseUri);
resource = baseUriResource.createRelative(schemaLocation);
if (resource.exists()) {
return createInputSource(resource);
}
} catch (IOException e) {
}
}
// let's try and find it on the classpath, see SWS-362
String classpathLocation = ResourceLoader.CLASSPATH_URL_PREFIX + "/" + schemaLocation;
resource = resourceLoader.getResource(classpathLocation);
if (resource.exists()) {
return createInputSource(resource);
}
}
return super.resolveEntity(namespace, schemaLocation, baseUri);
}Example 57
| Project: uPortal-master File: TemplateDataTenantOperationsListener.java View source code |
/**
* Given the list of resource strings, acquire the set of resource objects from a {@code
* org.springframework.core.io.ResourceLoader}.
*
* @param resourceLoader a resource loader, usually an application context
* @param resourcePaths set of resource paths as strings
* @return set of resources derived from paths via resource loader
*/
/*package*/
static Set<Resource> buildResourcesFromPaths(ResourceLoader resourceLoader, Set<String> resourcePaths) {
final Set<Resource> resourceSet = new HashSet<>();
for (String resourcePath : resourcePaths) {
Resource resource = resourceLoader.getResource(resourcePath);
log.debug("Resource {} exists?: {}", resource, resource.exists());
resourceSet.add(resource);
}
return resourceSet;
}Example 58
| Project: FunctionalTestsPortlet-master File: GenericPortletFilterBean.java View source code |
@Override
public void init(FilterConfig filterConfig) throws PortletException {
Assert.notNull(filterConfig, "FilterConfig must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Initializing filter '" + filterConfig.getFilterName() + "'");
}
this.filterConfig = filterConfig;
// Set bean properties from init parameters.
try {
PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new PortletContextResourceLoader(filterConfig.getPortletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
} catch (BeansException ex) {
String msg = "Failed to set bean properties on filter '" + filterConfig.getFilterName() + "': " + ex.getMessage();
logger.error(msg, ex);
throw new PortletException(msg, ex);
}
// Let subclasses do whatever initialization they like.
initFilterBean();
if (logger.isDebugEnabled()) {
logger.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully");
}
}Example 59
| Project: geoserver-master File: GeoServerSystemTestSupport.java View source code |
protected final void setUp(SystemTestData testData) throws Exception {
// speed up xpath evaluations
try {
// see
// http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance
Class.forName("com.sun.org.apache.xml.internal.dtm.ref.DTMManagerDefault");
System.setProperty("com.sun.org.apache.xml.internal.dtm.DTMManager", "com.sun.org.apache.xml.internal.dtm.ref.DTMManagerDefault");
} catch (Exception e) {
}
// disable security manager to speed up tests, we are spending a lot of time in privileged
// blocks
System.setSecurityManager(null);
// is loaded before GoeServer has a chance to setup logging for good)
try {
Logging.ALL.setLoggerFactory(Log4JLoggerFactory.getInstance());
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Could not configure log4j logging redirection", e);
}
System.setProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL, "true");
GeoServerResourceLoader loader = new GeoServerResourceLoader(testData.getDataDirectoryRoot());
LoggingUtils.configureGeoServerLogging(loader, getClass().getResourceAsStream(getLogConfiguration()), false, true, null);
setUpTestData(testData);
// put the mock http server in test mode
TestHttpClientProvider.startTest();
// if we have data, create a mock servlet context and start up the spring configuration
if (testData.isTestDataAvailable()) {
//set up a fake WEB-INF directory
org.springframework.core.io.ResourceLoader rl;
if (testData.getDataDirectoryRoot().canWrite()) {
File webinf = new File(testData.getDataDirectoryRoot(), "WEB-INF");
webinf.mkdir();
rl = new DirectoryResourceLoader(testData.getDataDirectoryRoot());
} else {
rl = new DefaultResourceLoader();
}
MockServletContext servletContext = new MockServletContext(rl);
// we are on servlet 2.4
servletContext.setMinorVersion(4);
servletContext.setInitParameter("GEOSERVER_DATA_DIR", testData.getDataDirectoryRoot().getPath());
servletContext.setInitParameter("serviceStrategy", "PARTIAL-BUFFER2");
List<String> contexts = new ArrayList();
setUpSpring(contexts);
applicationContext = new GeoServerTestApplicationContext(contexts.toArray(new String[contexts.size()]), servletContext);
applicationContext.setUseLegacyGeoServerLoader(false);
applicationContext.refresh();
applicationContext.publishEvent(new ContextLoadedEvent(applicationContext));
// set the parameter after a refresh because it appears a refresh
// wipes
// out all parameters
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
dispatcher = buildDispatcher();
onSetUp(testData);
}
}Example 60
| Project: grails-icu-master File: ICUPluginAwareResourceBundleMessageSource.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
if (Metadata.getCurrent().isWarDeployed()) {
localResourceLoader = resourceLoader;
} else {
// The "settings" may be null in some of the Grails unit tests.
BuildSettings settings = BuildSettingsHolder.getSettings();
String location = null;
if (settings != null) {
location = settings.getResourcesDir().getPath();
} else if (Environment.getCurrent().isReloadEnabled()) {
location = Environment.getCurrent().getReloadLocation();
}
if (location != null) {
localResourceLoader = new DevelopmentResourceLoader(application, location);
} else {
localResourceLoader = resourceLoader;
}
}
super.setResourceLoader(localResourceLoader);
if (resourceResolver == null) {
resourceResolver = new PathMatchingResourcePatternResolver(localResourceLoader);
}
}Example 61
| Project: hades-master File: DaoConfigDefinitionParser.java View source code |
/**
* Executes DAO auto configuration by scanning the provided entity package
* for classes implementing {@code Persistable}.
*
* @param configContext
* @param parserContext
*/
private void doAutoConfiguration(final DaoConfigContext configContext, final ParserContext parserContext) {
LOG.debug("Triggering auto DAO detection");
ResourceLoader resourceLoader = parserContext.getReaderContext().getResourceLoader();
// Detect available DAO interfaces
Set<String> daoInterfaces = getDaoInterfacesForAutoConfig(configContext, resourceLoader, parserContext.getReaderContext());
for (String daoInterface : daoInterfaces) {
registerGenericDaoFactoryBean(parserContext, DaoContext.fromInterfaceName(daoInterface, configContext));
}
}Example 62
| Project: iis-master File: WritePredefinedProjectProperties.java View source code |
/**
* Checks whether file exists.
* @param location
* @return true when exists, false otherwise.
*/
protected boolean exists(String location) {
if (StringUtils.isBlank(location)) {
return false;
}
File file = new File(location);
if (file.exists()) {
return true;
}
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource(location);
return resource.exists();
}Example 63
| Project: spring-flex-master File: FlexConfigurationManager.java View source code |
public List<String> getFiles(String dir) {
Resource parent = this.configurationPathStack.peek();
String dirPath = StringUtils.cleanPath(dir);
dirPath += dirPath.endsWith("/") ? "" : "/";
try {
Resource dirResource = parent.createRelative(dirPath);
Assert.isTrue(dirResource.exists(), "Flex configuration files could not be loaded from directory: " + dirPath);
Assert.isInstanceOf(ResourcePatternResolver.class, this.resourceLoader, "Cannot locate incuded resources using the current ResourceLoader - must be an instance of ResourcePatternResolver.");
ResourcePatternResolver resolver = (ResourcePatternResolver) this.resourceLoader;
Resource[] resources = resolver.getResources(dirResource.getURL().toString() + "*.xml");
List<String> result = new ArrayList<String>();
for (Resource resource : resources) {
Resource parentDir = parent.createRelative("/");
result.add(resource.getURL().toString().substring(parentDir.getURL().toString().length()));
}
return result;
} catch (IOException e) {
throw new IllegalStateException("Flex configuration files could not be loaded from directory: " + dirPath);
}
}Example 64
| Project: spring-webflow-master File: FlowDefinitionResourceFactory.java View source code |
/**
* Create an array of flow definition resources from the path pattern location provided.
* @param pattern the encoded {@link Resource} path pattern.
* @param attributes meta attributes to apply to each flow definition resource
* @return the flow definition resources
*/
public FlowDefinitionResource[] createResources(String pattern, AttributeMap<Object> attributes) throws IOException {
if (resourceLoader instanceof ResourcePatternResolver) {
ResourcePatternResolver resolver = (ResourcePatternResolver) resourceLoader;
Resource[] resources;
if (basePath == null) {
resources = resolver.getResources(pattern);
} else {
if (basePath.endsWith(SLASH) || pattern.startsWith(SLASH)) {
resources = resolver.getResources(basePath + pattern);
} else {
resources = resolver.getResources(basePath + SLASH + pattern);
}
}
FlowDefinitionResource[] flowResources = new FlowDefinitionResource[resources.length];
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
flowResources[i] = new FlowDefinitionResource(getFlowId(resource), resource, attributes);
}
return flowResources;
} else {
throw new IllegalStateException("Cannot create flow definition resources from patterns without a ResourceLoader configured that is a ResourcePatternResolver");
}
}Example 65
| Project: virgo.web-master File: TestController.java View source code |
@RequestMapping(value = "/appCtxGetResourceGetFile")
public void appCtxGetResourceGetFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
String path = getRequiredStringParameter(request, "path");
String output = "<html><head><title>Testing path [" + path + "]</title></head><body>";
Resource resource = this.resourceLoader.getResource(path);
File file = resource.getFile();
output += "From ApplicationContext/ResourceLoader's getResource().getFile() for [" + path + "]: file exists: " + file.exists() + "; canonical path: " + file.getCanonicalPath();
output += "</body></html>";
response.getWriter().write(output);
}Example 66
| Project: Broadleaf-eCommerce-master File: BroadleafGenericGroovyXmlWebContextLoader.java View source code |
/**
* Configures web resources for the supplied web application context (WAC).
*
* <h4>Implementation Details</h4>
*
* <p>If the supplied WAC has no parent or its parent is not a WAC, the
* supplied WAC will be configured as the Root WAC (see "<em>Root WAC
* Configuration</em>" below).
*
* <p>Otherwise the context hierarchy of the supplied WAC will be traversed
* to find the top-most WAC (i.e., the root); and the {@link ServletContext}
* of the Root WAC will be set as the {@code ServletContext} for the supplied
* WAC.
*
* <h4>Root WAC Configuration</h4>
*
* <ul>
* <li>The resource base path is retrieved from the supplied
* {@code WebMergedContextConfiguration}.</li>
* <li>A {@link ResourceLoader} is instantiated for the {@link MockServletContext}:
* if the resource base path is prefixed with "{@code classpath:/}", a
* {@link DefaultResourceLoader} will be used; otherwise, a
* {@link FileSystemResourceLoader} will be used.</li>
* <li>A {@code MockServletContext} will be created using the resource base
* path and resource loader.</li>
* <li>The supplied {@link MergeXmlWebApplicationContext} is then stored in
* the {@code MockServletContext} under the
* {@link MergeXmlWebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} key.</li>
* <li>Finally, the {@code MockServletContext} is set in the
* {@code MergeXmlWebApplicationContext}.</li>
*
* @param context the merge xml web application context for which to configure the web
* resources
* @param webMergedConfig the merged context configuration to use to load the
* merge xml web application context
*/
protected void configureWebResources(MergeXmlWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {
ApplicationContext parent = context.getParent();
// the Root WAC:
if (parent == null || (!(parent instanceof WebApplicationContext))) {
String resourceBasePath = webMergedConfig.getResourceBasePath();
ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() : new FileSystemResourceLoader();
ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
context.setServletContext(servletContext);
} else {
ServletContext servletContext = null;
// find the Root WAC
while (parent != null) {
if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
servletContext = ((WebApplicationContext) parent).getServletContext();
break;
}
parent = parent.getParent();
}
Assert.state(servletContext != null, "Failed to find Root MergeXmlWebApplicationContext in the context hierarchy");
context.setServletContext(servletContext);
}
}Example 67
| Project: BroadleafCommerce-master File: BroadleafGenericGroovyXmlWebContextLoader.java View source code |
/**
* Configures web resources for the supplied web application context (WAC).
*
* <h4>Implementation Details</h4>
*
* <p>If the supplied WAC has no parent or its parent is not a WAC, the
* supplied WAC will be configured as the Root WAC (see "<em>Root WAC
* Configuration</em>" below).
*
* <p>Otherwise the context hierarchy of the supplied WAC will be traversed
* to find the top-most WAC (i.e., the root); and the {@link ServletContext}
* of the Root WAC will be set as the {@code ServletContext} for the supplied
* WAC.
*
* <h4>Root WAC Configuration</h4>
*
* <ul>
* <li>The resource base path is retrieved from the supplied
* {@code WebMergedContextConfiguration}.</li>
* <li>A {@link ResourceLoader} is instantiated for the {@link MockServletContext}:
* if the resource base path is prefixed with "{@code classpath:/}", a
* {@link DefaultResourceLoader} will be used; otherwise, a
* {@link FileSystemResourceLoader} will be used.</li>
* <li>A {@code MockServletContext} will be created using the resource base
* path and resource loader.</li>
* <li>The supplied {@link MergeXmlWebApplicationContext} is then stored in
* the {@code MockServletContext} under the
* {@link MergeXmlWebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} key.</li>
* <li>Finally, the {@code MockServletContext} is set in the
* {@code MergeXmlWebApplicationContext}.</li>
*
* @param context the merge xml web application context for which to configure the web
* resources
* @param webMergedConfig the merged context configuration to use to load the
* merge xml web application context
*/
protected void configureWebResources(MergeXmlWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {
ApplicationContext parent = context.getParent();
// the Root WAC:
if (parent == null || (!(parent instanceof WebApplicationContext))) {
String resourceBasePath = webMergedConfig.getResourceBasePath();
ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() : new FileSystemResourceLoader();
ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
context.setServletContext(servletContext);
} else {
ServletContext servletContext = null;
// find the Root WAC
while (parent != null) {
if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
servletContext = ((WebApplicationContext) parent).getServletContext();
break;
}
parent = parent.getParent();
}
Assert.state(servletContext != null, "Failed to find Root MergeXmlWebApplicationContext in the context hierarchy");
context.setServletContext(servletContext);
}
}Example 68
| Project: commerce-master File: BroadleafGenericGroovyXmlWebContextLoader.java View source code |
/**
* Configures web resources for the supplied web application context (WAC).
*
* <h4>Implementation Details</h4>
*
* <p>If the supplied WAC has no parent or its parent is not a WAC, the
* supplied WAC will be configured as the Root WAC (see "<em>Root WAC
* Configuration</em>" below).
*
* <p>Otherwise the context hierarchy of the supplied WAC will be traversed
* to find the top-most WAC (i.e., the root); and the {@link ServletContext}
* of the Root WAC will be set as the {@code ServletContext} for the supplied
* WAC.
*
* <h4>Root WAC Configuration</h4>
*
* <ul>
* <li>The resource base path is retrieved from the supplied
* {@code WebMergedContextConfiguration}.</li>
* <li>A {@link ResourceLoader} is instantiated for the {@link MockServletContext}:
* if the resource base path is prefixed with "{@code classpath:/}", a
* {@link DefaultResourceLoader} will be used; otherwise, a
* {@link FileSystemResourceLoader} will be used.</li>
* <li>A {@code MockServletContext} will be created using the resource base
* path and resource loader.</li>
* <li>The supplied {@link MergeXmlWebApplicationContext} is then stored in
* the {@code MockServletContext} under the
* {@link MergeXmlWebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} key.</li>
* <li>Finally, the {@code MockServletContext} is set in the
* {@code MergeXmlWebApplicationContext}.</li>
*
* @param context the merge xml web application context for which to configure the web
* resources
* @param webMergedConfig the merged context configuration to use to load the
* merge xml web application context
*/
protected void configureWebResources(MergeXmlWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {
ApplicationContext parent = context.getParent();
// the Root WAC:
if (parent == null || (!(parent instanceof WebApplicationContext))) {
String resourceBasePath = webMergedConfig.getResourceBasePath();
ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() : new FileSystemResourceLoader();
ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
context.setServletContext(servletContext);
} else {
ServletContext servletContext = null;
// find the Root WAC
while (parent != null) {
if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
servletContext = ((WebApplicationContext) parent).getServletContext();
break;
}
parent = parent.getParent();
}
Assert.state(servletContext != null, "Failed to find Root MergeXmlWebApplicationContext in the context hierarchy");
context.setServletContext(servletContext);
}
}Example 69
| Project: OpenClinica-master File: CoreResources.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
try {
// setPROPERTIES_DIR(resourceLoader);
// @pgawade 18-April-2011 Fix for issue 8394
webapp = getWebAppName(resourceLoader.getResource("/").getURI().getPath());
/* getPropertiesSource();
String filePath = "$catalina.home/$WEBAPP.lower.config";
filePath = replaceWebapp(filePath);
filePath = replaceCatHome(filePath);
String dataInfoPropFileName = filePath + "/datainfo.properties";
String extractPropFileName = filePath + "/extract.properties";
Properties OC_dataDataInfoProperties = getPropValues(dataInfoProp, dataInfoPropFileName);
Properties OC_dataExtractProperties = getPropValues(extractProp, extractPropFileName);
if (OC_dataDataInfoProperties != null)
dataInfo = OC_dataDataInfoProperties;
if (OC_dataExtractProperties != null)
extractInfo = OC_dataExtractProperties;
*/
String dbName = dataInfo.getProperty("dbType");
DATAINFO = dataInfo;
// weird, but there are references to dataInfo...MainMenuServlet for
dataInfo = setDataInfoProperties();
// instance
EXTRACTINFO = extractInfo;
DB_NAME = dbName;
SQLFactory factory = SQLFactory.getInstance();
factory.run(dbName, resourceLoader);
setODM_MAPPING_DIR();
if (extractInfo != null) {
copyBaseToDest(resourceLoader);
// @pgawade 18-April-2011 Fix for issue 8394
copyODMMappingXMLtoResources(resourceLoader);
extractProperties = findExtractProperties();
// JN: this is in for junits to run without extract props
copyImportRulesFiles();
// copyConfig();
}
// tbh, following line to be removed
// reportUrl();
} catch (OpenClinicaSystemException e) {
logger.debug(e.getMessage());
logger.debug(e.toString());
throw new OpenClinicaSystemException(e.getMessage(), e.fillInStackTrace());
} catch (Exception e) {
e.printStackTrace();
}
}Example 70
| Project: spring-data-jdbc-ext-master File: PoolingDataSourceBeanDefinitionParser.java View source code |
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
ResourceLoader rl = parserContext.getReaderContext().getResourceLoader();
//attributes
String propertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE);
String connectionPropertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE);
String connectionPropertyPrefix = element.getAttribute(CONNECTION_PROPERTIES_PREFIX_ATTRIBUTE);
String cachingPropertyPrefix = element.getAttribute(CONNECTON_CACHE_PROPERTIS_PREFIX_ATTRIBUTE);
String url = element.getAttribute(URL_ATTRIBUTE);
String username = element.getAttribute(USERNAME_ATTRIBUTE);
String password = element.getAttribute(PASSWORD_ATTRIBUTE);
String onsConfiguration = element.getAttribute(ONS_CONFIGURATION_ATTRIBUTE);
String fastConnectionFailoverEnabled = element.getAttribute(FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE);
String connectionCachingEnabled = element.getAttribute(CONNECTION_CACHING_ENABLED_ATTRIBUTE);
boolean propertyFileProvided = false;
Map<String, Object> providedProperties = new HashMap<String, Object>();
// defaults
if (!StringUtils.hasText(propertyFileLocation) && !StringUtils.hasText(connectionPropertyFileLocation)) {
propertyFileLocation = DEFAULT_PROPERTY_FILE_LOCATION;
}
if (!StringUtils.hasText(connectionPropertyPrefix)) {
connectionPropertyPrefix = DEFAULT_PROPERTY_PREFIX;
}
// look for property files
if (StringUtils.hasText(propertyFileLocation)) {
logger.debug("Using properties location: " + propertyFileLocation);
String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(propertyFileLocation);
Resource r = rl.getResource(resolvedLocation);
logger.debug("Loading properties from resource: " + r);
PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
factoryBean.setLocation(r);
try {
factoryBean.afterPropertiesSet();
Properties resource = factoryBean.getObject();
for (Map.Entry<Object, Object> entry : resource.entrySet()) {
providedProperties.put((String) entry.getKey(), entry.getValue());
}
propertyFileProvided = true;
} catch (FileNotFoundException e) {
propertyFileProvided = false;
if (propertyFileLocation.equals(DEFAULT_PROPERTY_FILE_LOCATION)) {
logger.debug("Unable to find " + propertyFileLocation);
} else {
parserContext.getReaderContext().error("pooling-datasource defined with attribute '" + PROPERTIES_LOCATION_ATTRIBUTE + "' but the property file was not found at location \"" + propertyFileLocation + "\"", element);
}
} catch (IOException e) {
logger.warn("Error loading " + propertyFileLocation + ": " + e.getMessage());
}
} else {
propertyFileProvided = false;
}
if (logger.isDebugEnabled()) {
logger.debug("Using provided properties: " + providedProperties);
}
if (connectionPropertyPrefix == null) {
connectionPropertyPrefix = "";
}
if (connectionPropertyPrefix.length() > 0 && !connectionPropertyPrefix.endsWith(".")) {
connectionPropertyPrefix = connectionPropertyPrefix + ".";
}
logger.debug("Using connection properties prefix: " + connectionPropertyPrefix);
if (cachingPropertyPrefix == null) {
cachingPropertyPrefix = "";
}
if (cachingPropertyPrefix.length() > 0 && !cachingPropertyPrefix.endsWith(".")) {
cachingPropertyPrefix = cachingPropertyPrefix + ".";
}
logger.debug("Using caching properties prefix: " + cachingPropertyPrefix);
if (!(StringUtils.hasText(connectionCachingEnabled) || providedProperties.containsKey(attributeToPropertyMap.get(CONNECTION_CACHING_ENABLED_ATTRIBUTE)))) {
connectionCachingEnabled = DEFAULT_CONNECTION_CACHING_ENABLED;
}
setRequiredAttribute(builder, parserContext, element, providedProperties, connectionPropertyPrefix, propertyFileProvided, url, URL_ATTRIBUTE, "URL");
setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, username, USERNAME_ATTRIBUTE);
setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, password, PASSWORD_ATTRIBUTE);
setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, connectionCachingEnabled, CONNECTION_CACHING_ENABLED_ATTRIBUTE);
setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, fastConnectionFailoverEnabled, FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE);
setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, onsConfiguration, ONS_CONFIGURATION_ATTRIBUTE);
Properties providedConnectionProperties = new Properties();
Properties providedCachingProperties = new Properties();
for (String key : providedProperties.keySet()) {
if (StringUtils.hasText(connectionPropertyPrefix) && key.startsWith(connectionPropertyPrefix)) {
String newKey = key.substring(connectionPropertyPrefix.length());
providedConnectionProperties.put(newKey, providedProperties.get(key));
} else {
if (StringUtils.hasText(cachingPropertyPrefix) && key.startsWith(cachingPropertyPrefix)) {
String newKey = key.substring(cachingPropertyPrefix.length());
providedCachingProperties.put(newKey, providedProperties.get(key));
} else {
providedConnectionProperties.put(key, providedProperties.get(key));
}
}
}
// look for connectionProperties
Object connProperties = DomUtils.getChildElementValueByTagName(element, CONNECTION_PROPERTIES_CHILD_ELEMENT);
if (connProperties != null) {
if (logger.isDebugEnabled()) {
logger.debug("Using connection-properties");
}
builder.addPropertyValue("connectionProperties", connProperties);
} else {
if (providedConnectionProperties.size() > 0) {
if (logger.isDebugEnabled()) {
logger.debug("Using provided connection properties: " + providedConnectionProperties);
}
builder.addPropertyValue("connectionProperties", providedConnectionProperties);
}
}
// look for connectionCacheProperties
Object cacheProperties = DomUtils.getChildElementValueByTagName(element, CONNECTION_CACHE_PROPERTIES_CHILD_ELEMENT);
if (cacheProperties != null) {
if (logger.isDebugEnabled()) {
logger.debug("Using connection-cache-properties: [" + cacheProperties + "]");
}
builder.addPropertyValue("connectionCacheProperties", cacheProperties);
} else {
if (providedCachingProperties.size() > 0) {
if (logger.isDebugEnabled()) {
logger.debug("Using provided caching properties: " + providedCachingProperties);
}
builder.addPropertyValue("connectionCacheProperties", providedCachingProperties);
}
}
builder.setRole(BeanDefinition.ROLE_SUPPORT);
}Example 71
| Project: spring-ide-master File: BeansConfig.java View source code |
/**
* {@inheritDoc}
*/
@Override
protected void readConfig() {
if (!this.isModelPopulated) {
long start = System.currentTimeMillis();
long count = 0;
w.lock();
if (this.isModelPopulated) {
w.unlock();
return;
}
final ClassLoader projectIncludingClassloader = getProjectRelatedClassLoader();
try {
// Publish start events
for (IBeansConfigEventListener eventListener : eventListeners) {
eventListener.onReadStart(this);
}
if (file != null && file.exists()) {
// Only install Eclipse-based resource loader if enabled in project properties
// IMPORTANT: the following block needs to stay before the w.lock()
// as it could otherwise create a runtime deadlock
final ResourceLoader resourceLoader;
if (getElementParent() instanceof IBeansProject && ((IBeansProject) getElementParent()).isImportsEnabled()) {
resourceLoader = new EclipsePathMatchingResourcePatternResolver(file.getProject(), projectIncludingClassloader);
} else {
resourceLoader = new ClassResourceFilteringPatternResolver(file.getProject(), projectIncludingClassloader);
}
modificationTimestamp = file.getModificationStamp();
if (isArchived) {
if (file instanceof Resource) {
resource = (Resource) file;
} else {
resource = new StorageResource(new ZipEntryStorage(file.getProject(), getElementName()), file.getProject());
}
} else {
resource = new FileResource(file);
}
// Set up classloader to use for NamespaceHandler and XSD loading
ClassLoader namespaceResolvingClassloader = projectIncludingClassloader;
if (!NamespaceUtils.useNamespacesFromClasspath(file.getProject())) {
namespaceResolvingClassloader = BeansCorePlugin.getClassLoader();
}
registry = new ScannedGenericBeanDefinitionSuppressingBeanDefinitionRegistry();
EntityResolver resolver = new XmlCatalogDelegatingEntityResolver(new BeansDtdResolver(), new PluggableSchemaResolver(namespaceResolvingClassloader));
final DocumentAccessor documentAccessor = new DocumentAccessor();
final SourceExtractor sourceExtractor = new DelegatingSourceExtractor(file.getProject());
final BeansConfigReaderEventListener eventListener = new BeansConfigReaderEventListener(this, resource, sourceExtractor, documentAccessor);
final NamespaceHandlerResolver namespaceHandlerResolver = new DelegatingNamespaceHandlerResolver(namespaceResolvingClassloader, this, documentAccessor);
problemReporter = new BeansConfigProblemReporter();
beanNameGenerator = new UniqueBeanNameGenerator(this);
final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry) {
@Override
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
// create the validation error on the correct resource
if (encodedResource != null && encodedResource.getResource() instanceof IAdaptable) {
currentResource = (IResource) ((IAdaptable) encodedResource.getResource()).getAdapter(IResource.class);
currentEncodedResource = encodedResource;
}
try {
// Delegate actual processing to XmlBeanDefinitionReader
int loadedBeans = 0;
if (encodedResource.getResource().exists()) {
loadedBeans = super.loadBeanDefinitions(encodedResource);
}
return loadedBeans;
} finally {
// Reset currently processed resource before leaving
currentResource = null;
currentEncodedResource = null;
}
}
@Override
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
try {
documentAccessor.pushDocument(doc);
return super.registerBeanDefinitions(doc, resource);
} finally {
documentAccessor.popDocument();
}
}
@Override
public XmlReaderContext createReaderContext(Resource resource) {
return new ProfileAwareReaderContext(resource, problemReporter, eventListener, sourceExtractor, this, namespaceHandlerResolver);
}
@Override
protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {
return new ToolingFriendlyBeanDefinitionDocumentReader(BeansConfig.this);
}
};
reader.setDocumentLoader(new XercesDocumentLoader());
reader.setResourceLoader(resourceLoader);
reader.setEntityResolver(resolver);
reader.setSourceExtractor(sourceExtractor);
reader.setEventListener(eventListener);
reader.setProblemReporter(problemReporter);
reader.setErrorHandler(new BeansConfigErrorHandler());
reader.setNamespaceHandlerResolver(namespaceHandlerResolver);
reader.setBeanNameGenerator(beanNameGenerator);
reader.setEnvironment(new ToolingAwareEnvironment());
final Map<Throwable, Integer> throwables = new HashMap<Throwable, Integer>();
try {
Callable<Integer> loadBeanDefinitionOperation = new Callable<Integer>() {
public Integer call() {
// Obtain thread context classloader and override with the project classloader
ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(resourceLoader.getClassLoader());
try {
// Load bean definitions
int count = reader.loadBeanDefinitions(resource);
// Finally register post processed beans and components
eventListener.registerComponents();
// Post process beans config if required
postProcess(resourceLoader.getClassLoader());
return count;
} catch (Exception e) {
throwables.put(e, LineNumberPreservingDOMParser.getStartLineNumber(documentAccessor.getLastElement()));
} finally {
// Reset the context classloader
Thread.currentThread().setContextClassLoader(threadClassLoader);
}
return 0;
}
};
try {
FutureTask<Integer> task = new FutureTask<Integer>(loadBeanDefinitionOperation);
BeansCorePlugin.getExecutorService().submit(task);
count = task.get(BeansCorePlugin.getDefault().getPreferenceStore().getInt(BeansCorePlugin.TIMEOUT_CONFIG_LOADING_PREFERENCE_ID), TimeUnit.SECONDS);
// if we recored an exception use this instead of stupid concurrent exception
if (throwables.size() > 0) {
throw throwables.keySet().iterator().next();
}
} catch (TimeoutException e) {
problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR, "Loading of resource '" + resource.getFile().getAbsolutePath() + "' took more than " + BeansCorePlugin.getDefault().getPreferenceStore().getInt(BeansCorePlugin.TIMEOUT_CONFIG_LOADING_PREFERENCE_ID) + "sec", file, 1));
}
} catch (Throwable e) {
int line = -1;
if (throwables.containsKey(e)) {
line = throwables.get(e);
}
if (e instanceof BeanDefinitionStoreException) {
if (e.getCause() != null) {
problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR, String.format("Error occured processing XML '%s'. See Error Log for more details", e.getCause().getMessage()), file, line));
BeansCorePlugin.log(new Status(IStatus.INFO, BeansCorePlugin.PLUGIN_ID, String.format("Error occured processing '%s'", file.getFullPath()), e.getCause()));
} else {
problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR, e.getMessage(), file, line));
BeansCorePlugin.log(new Status(IStatus.INFO, BeansCorePlugin.PLUGIN_ID, String.format("Error occured processing '%s'", file.getFullPath()), e));
}
} else if (!(e.getCause() instanceof SAXParseException) && !(e instanceof BeanDefinitionParsingException)) {
problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR, e.getMessage(), file, line));
BeansCorePlugin.log(new Status(IStatus.INFO, BeansCorePlugin.PLUGIN_ID, String.format("Error occured processing '%s'", file.getFullPath()), e));
}
}
}
} finally {
// Prepare the internal cache of all children for faster access
List<ISourceModelElement> allChildren = new ArrayList<ISourceModelElement>(imports);
allChildren.addAll(aliases.values());
allChildren.addAll(components);
allChildren.addAll(beans.values());
Collections.sort(allChildren, new Comparator<ISourceModelElement>() {
public int compare(ISourceModelElement element1, ISourceModelElement element2) {
return element1.getElementStartLine() - element2.getElementStartLine();
}
});
this.children = allChildren.toArray(new IModelElement[allChildren.size()]);
this.isModelPopulated = true;
w.unlock();
// Run external post processors
postProcessExternal(externalPostProcessors.keySet(), projectIncludingClassloader);
// Publish events for all existing post processors
if (this.ownPostProcessors != null) {
for (IBeansConfigPostProcessor postProcessor : ownPostProcessors) {
for (IBeansConfigEventListener eventListener : eventListeners) {
eventListener.onPostProcessorDetected(this, postProcessor);
}
}
}
// Publish events for all removed post processors
if (this.removedPostProcessors != null) {
for (IBeansConfigPostProcessor postProcessor : removedPostProcessors) {
for (IBeansConfigEventListener eventListener : eventListeners) {
eventListener.onPostProcessorRemoved(this, postProcessor);
}
}
}
for (IBeansConfigEventListener eventListener : eventListeners) {
eventListener.onReadEnd(this);
}
if (DEBUG) {
System.out.println(String.format("> loading of %s beans from %s took %sms", count, file.getFullPath().toString(), (System.currentTimeMillis() - start)));
}
}
}
}Example 72
| Project: alfresco-etl-connector-master File: ContentImporterComponentBase.java View source code |
/* (non-Javadoc)
* @see org.alfresco.service.cmr.view.ImportStreamHandler#importStream(java.lang.String)
*/
public InputStream importStream(String content) {
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource(content);
if (resource.exists() == false) {
throw new ImporterException("Content URL " + content + " does not exist.");
}
try {
return resource.getInputStream();
} catch (IOException e) {
throw new ImporterException("Failed to retrieve input stream for content URL " + content);
}
}Example 73
| Project: spring-js-master File: AbstractApplicationContext.java View source code |
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
if (!beanFactory.containsBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
Map systemProperties;
try {
systemProperties = System.getProperties();
} catch (AccessControlException ex) {
systemProperties = new ReadOnlySystemAttributesMap() {
@Override
protected String getSystemAttribute(String propertyName) {
try {
return System.getProperty(propertyName);
} catch (AccessControlException ex) {
if (logger.isInfoEnabled()) {
logger.info("Not allowed to obtain system property [" + propertyName + "]: " + ex.getMessage());
}
return null;
}
}
};
}
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, systemProperties);
}
if (!beanFactory.containsBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
Map<String, String> systemEnvironment;
try {
systemEnvironment = System.getenv();
} catch (AccessControlException ex) {
systemEnvironment = new ReadOnlySystemAttributesMap() {
@Override
protected String getSystemAttribute(String variableName) {
try {
return System.getenv(variableName);
} catch (AccessControlException ex) {
if (logger.isInfoEnabled()) {
logger.info("Not allowed to obtain system environment variable [" + variableName + "]: " + ex.getMessage());
}
return null;
}
}
};
}
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, systemEnvironment);
}
}Example 74
| Project: spring-hadoop-samples-old-master File: JdbcPasswordRepository.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 75
| Project: camunda-bpm-spring-boot-master File: ResourceLoadingProcessEnginesFilter.java View source code |
/**
* @return the resourceLoader
*/
public ResourceLoader getResourceLoader() {
return resourceLoader;
}Example 76
| Project: camunda-bpm-spring-boot-starter-master File: ResourceLoadingProcessEnginesFilter.java View source code |
/**
* @return the resourceLoader
*/
public ResourceLoader getResourceLoader() {
return resourceLoader;
}Example 77
| Project: longneck-dns-master File: DnsHook.java View source code |
@Override
public void setResourceLoader(ResourceLoader rl) {
resourceLoader = rl;
}Example 78
| Project: longneck-lookup-master File: LookupHook.java View source code |
@Override
public void setResourceLoader(ResourceLoader rl) {
resourceLoader = rl;
}Example 79
| Project: longneck-weblog-master File: WeblogParserHook.java View source code |
@Override
public void setResourceLoader(ResourceLoader rl) {
resourceLoader = rl;
}Example 80
| Project: spring-data-book-master File: AnalysisService.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 81
| Project: cosmos-message-master File: ConfigurationLoader.java View source code |
public static Resource getConfigFile(String fileName) {
ResourceLoader loader = new DefaultResourceLoader();
return loader.getResource("file:" + InitConfigPath.getParamsRoot() + File.separator + "files" + File.separator + fileName);
}Example 82
| Project: dynamic-extensions-for-alfresco-master File: AbstractConfigurationFileFactoryBean.java View source code |
/* Dependencies */
@Override
public void setResourceLoader(final ResourceLoader resourceLoader) {
Assert.isInstanceOf(ResourcePatternResolver.class, resourceLoader);
this.resourcePatternResolver = (ResourcePatternResolver) resourceLoader;
}Example 83
| Project: eql-master File: EqlerScannerRegistrar.java View source code |
/**
* {@inheritDoc}
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 84
| Project: glados-wiki-master File: MultipartResolverContext.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 85
| Project: OrganicBuilder-master File: ComposedLevelFactory.java View source code |
@Override
public void setResourceLoader(final ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 86
| Project: riot-master File: ResourceTemplateLoader.java View source code |
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 87
| Project: spring-boot-jade-master File: JadeResourceTemplateLoader.java View source code |
/**
* @param resourceLoader the resourceLoader to set
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 88
| Project: spring-rest-client-master File: SpringRestClientScannerRegistrar.java View source code |
/**
* {@inheritDoc}
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 89
| Project: cmestemp22-master File: ResourcePropertyFileLoaderFactoryBean.java View source code |
/**
* {@inheritDoc}
*/
@Override
public void setResourceLoader(final ResourceLoader inResourceLoader) {
resourceLoader = inResourceLoader;
}Example 90
| Project: effectivejava-master File: SortedResourcesFactoryBean.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}Example 91
| Project: eurekastreams-master File: ResourcePropertyFileLoaderFactoryBean.java View source code |
/**
* {@inheritDoc}
*/
@Override
public void setResourceLoader(final ResourceLoader inResourceLoader) {
resourceLoader = inResourceLoader;
}Example 92
| Project: head-master File: ResourceOpener.java View source code |
private String adjustClasspath(String file) {
return isClasspathPrefixPresent(changeLog) && !isClasspathPrefixPresent(file) ? ResourceLoader.CLASSPATH_URL_PREFIX + file : file;
}Example 93
| Project: initializr-master File: TemplateRenderer.java View source code |
private static TemplateLoader mustacheTemplateLoader() {
ResourceLoader resourceLoader = new DefaultResourceLoader();
String prefix = "classpath:/templates/";
Charset charset = Charset.forName("UTF-8");
return name -> new InputStreamReader(resourceLoader.getResource(prefix + name).getInputStream(), charset);
}Example 94
| Project: liquigraph-master File: LiquigraphAutoConfiguration.java View source code |
@Bean
public SpringLiquigraph liquigraph(ResourceLoader loader) throws IOException {
final SpringChangelogLoader changelogLoader = new SpringChangelogLoader(loader);
return new SpringLiquigraph(getDataSource(), changelogLoader, properties.getChangeLog());
}Example 95
| Project: MavenOneCMDB-master File: ResourceProvider.java View source code |
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 96
| Project: mifos-head-master File: ResourceOpener.java View source code |
private String adjustClasspath(String file) {
return isClasspathPrefixPresent(changeLog) && !isClasspathPrefixPresent(file) ? ResourceLoader.CLASSPATH_URL_PREFIX + file : file;
}Example 97
| Project: MybatisSpring2.5.X-master File: MapperScannerRegistrar.java View source code |
/**
* {@inheritDoc}
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 98
| Project: spring-batch-admin-master File: FileServiceResourceConverter.java View source code |
/**
* Set the resource loader as a fallback for resources that are not managed
* by the {@link FileService}.
*
* @see ResourceLoaderAware#setResourceLoader(ResourceLoader)
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 99
| Project: spring-cloud-config-master File: GenericResourceRepository.java View source code |
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}Example 100
| Project: spring-modules-validation-master File: ValangCondition.java View source code |
public void setResourceLoader(ResourceLoader resourceLoader) {
parser.setResourceLoader(resourceLoader);
}Example 101
| Project: spring-ws-test-master File: AbstractResourceLookup.java View source code |
public ResourceLoader getResourceLoader() {
return resourceLoader;
}