下面列出了org.springframework.context.ApplicationContextAware#org.springframework.core.io.ResourceLoader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public String execute()
throws Exception
{
List<Locale> locales = localeManager.getLocalesOrderedByPriority();
ResourceLoader resourceLoader = new DefaultResourceLoader();
for ( Locale locale : locales )
{
String helpPage = helpPagePreLocale + locale.toString() + helpPagePostLocale;
if ( resourceLoader.getResource( helpPage ) != null )
{
this.helpPage = helpPage;
return SUCCESS;
}
}
return SUCCESS;
}
@Test
public void testLoadFileFromFilesystem() throws IOException
{
Resource resource = mockResource(ABSOLUTE_PATH, mockFileForUpload(), false);
ResourceLoader resourceLoader = mockResourceLoader(resource);
when(resourceLoader.getResource(ResourceUtils.FILE_URL_PREFIX + FILE_PATH)).thenReturn(resource);
mockRemoteWebDriver();
WebDriver webDriver = mock(WebDriver.class, withSettings().extraInterfaces(WrapsDriver.class));
when(webDriverProvider.get()).thenReturn(webDriver);
when(softAssert.assertTrue(FILE_FILE_PATH_EXISTS, true)).thenReturn(true);
when(webDriverProvider.isRemoteExecution()).thenReturn(true);
SearchAttributes searchAttributes = new SearchAttributes(ActionAttributeType.XPATH,
new SearchParameters(XPATH).setVisibility(Visibility.ALL));
when(baseValidations.assertIfElementExists(AN_ELEMENT, searchAttributes)).thenReturn(webElement);
elementSteps.uploadFile(searchAttributes, FILE_PATH);
verify(webElement).sendKeys(ABSOLUTE_PATH);
}
public FirebaseApplicationService(ResourceLoader resourceLoader, FirebaseConfigurationProperties firebaseConfigurationProperties) throws IOException {
this.firebaseConfigurationProperties = firebaseConfigurationProperties;
this.resourceLoader = resourceLoader;
assert firebaseConfigurationProperties.getServiceAccountFilename() != null;
assert firebaseConfigurationProperties.getRealtimeDatabaseUrl() != null;
// file: or classpath:
Resource serviceAccount = resourceLoader.getResource(firebaseConfigurationProperties.getServiceAccountFilename());
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount.getInputStream()))
.setDatabaseUrl(firebaseConfigurationProperties.getRealtimeDatabaseUrl())
.build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
}
GoogleCredential googleCred = GoogleCredential.fromStream(serviceAccount.getInputStream());
scoped = googleCred.createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.database", "https://www.googleapis.com/auth/userinfo.email"));
scoped.refreshToken();
}
/**
* Provide a lazy {@link FetchingCacheService} instance if one hasn't already been defined.
*
* @param resourceLoader The Spring Resource loader to use
* @param cacheArguments The cache command line arguments to use
* @param fileLockFactory The file lock factory to use
* @param taskExecutor The task executor to use
* @return A {@link FetchingCacheServiceImpl} instance
* @throws IOException On error creating the instance
*/
@Bean
@Lazy
@ConditionalOnMissingBean(FetchingCacheService.class)
public FetchingCacheService fetchingCacheService(
final ResourceLoader resourceLoader,
final ArgumentDelegates.CacheArguments cacheArguments,
final FileLockFactory fileLockFactory,
@Qualifier("sharedAgentTaskExecutor") final TaskExecutor taskExecutor
) throws IOException {
return new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
taskExecutor
);
}
@Override
public MetadataReader getMetadataReader(String className) throws IOException {
String resourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(className) + ClassUtils.CLASS_FILE_SUFFIX;
Resource resource = this.resourceLoader.getResource(resourcePath);
if (!resource.exists()) {
// Maybe an inner class name using the dot name syntax? Need to use the dollar syntax here...
// ClassUtils.forName has an equivalent check for resolution into Class references later on.
int lastDotIndex = className.lastIndexOf('.');
if (lastDotIndex != -1) {
String innerClassName =
className.substring(0, lastDotIndex) + '$' + className.substring(lastDotIndex + 1);
String innerClassResourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(innerClassName) + ClassUtils.CLASS_FILE_SUFFIX;
Resource innerClassResource = this.resourceLoader.getResource(innerClassResourcePath);
if (innerClassResource.exists()) {
resource = innerClassResource;
}
}
}
return getMetadataReader(resource);
}
/**
* Constructor.
*
* @param properties properties
* @param taskScheduler task scheduler
* @param executorService executor service
* @param scriptEngineManager script engine manager
* @param resourceLoader resource loader
* @param meterRegistry meter registry
*/
public ScriptManager(
final ScriptManagerProperties properties,
final TaskScheduler taskScheduler,
final ExecutorService executorService,
final ScriptEngineManager scriptEngineManager,
final ResourceLoader resourceLoader,
final MeterRegistry meterRegistry
) {
this.properties = properties;
this.taskScheduler = taskScheduler;
this.executorService = executorService;
this.scriptEngineManager = scriptEngineManager;
this.resourceLoader = resourceLoader;
this.meterRegistry = meterRegistry;
}
@Bean
public ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate(
ReactiveRedisConnectionFactory reactiveRedisConnectionFactory, ResourceLoader resourceLoader) {
FstSerializationRedisSerializer serializer = new FstSerializationRedisSerializer(() -> {
FSTConfiguration configuration = FSTConfiguration.createDefaultConfiguration()
.setForceSerializable(true);
configuration.setClassLoader(resourceLoader.getClassLoader());
return configuration;
});
@SuppressWarnings("all")
RedisSerializationContext<Object, Object> serializationContext = RedisSerializationContext
.newSerializationContext()
.key((RedisSerializer)new StringRedisSerializer())
.value(serializer)
.hashKey(StringRedisSerializer.UTF_8)
.hashValue(serializer)
.build();
return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, serializationContext);
}
@Bean
@Conditional({ SchedulerConfiguration.SchedulerConfigurationPropertyChecker.class })
public SchedulerService schedulerService(CommonApplicationProperties commonApplicationProperties,
List<TaskPlatform> taskPlatforms, TaskDefinitionRepository taskDefinitionRepository,
AppRegistryService registry, ResourceLoader resourceLoader,
ApplicationConfigurationMetadataResolver metaDataResolver,
SchedulerServiceProperties schedulerServiceProperties,
AuditRecordService auditRecordService,
TaskConfigurationProperties taskConfigurationProperties,
DataSourceProperties dataSourceProperties) {
return new DefaultSchedulerService(commonApplicationProperties,
taskPlatforms, taskDefinitionRepository,
registry, resourceLoader,
taskConfigurationProperties, dataSourceProperties, null,
metaDataResolver, schedulerServiceProperties, auditRecordService);
}
/**
* Constructor.
*
* @param resourceLoader The application resource loader used to get references to resources
* @param dataServices The {@link DataServices} instance to use
* @param agentFileStreamService The service providing file manifest for active agent jobs
* @param archivedJobService The {@link ArchivedJobService} implementation to use to get archived
* job data
* @param meterRegistry The meter registry used to keep track of metrics
* @param jobFileService The service responsible for managing the job directory for V3 Jobs
* @param jobDirectoryManifestCreatorService The job directory manifest service
* @param agentRoutingService The agent routing service
*/
public JobDirectoryServerServiceImpl(
final ResourceLoader resourceLoader,
final DataServices dataServices,
final AgentFileStreamService agentFileStreamService,
final ArchivedJobService archivedJobService,
final MeterRegistry meterRegistry,
final JobFileService jobFileService,
final JobDirectoryManifestCreatorService jobDirectoryManifestCreatorService,
final AgentRoutingService agentRoutingService
) {
this(
resourceLoader,
dataServices,
agentFileStreamService,
archivedJobService,
new GenieResourceHandler.Factory(),
meterRegistry,
jobFileService,
jobDirectoryManifestCreatorService,
agentRoutingService
);
}
public ApiBootMyBatisEnhanceAutoConfiguration(ApiBootMyBatisEnhanceProperties properties,
ObjectProvider<Interceptor[]> interceptorsProvider,
ResourceLoader resourceLoader,
ObjectProvider<DatabaseIdProvider> databaseIdProvider,
ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
ObjectProvider<List<SqlSessionFactoryBeanCustomizer>> sqlSessionFactoryBeanCustomizersProvider) {
this.properties = properties;
this.interceptors = interceptorsProvider.getIfAvailable();
this.resourceLoader = resourceLoader;
this.databaseIdProvider = databaseIdProvider.getIfAvailable();
this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
this.sqlSessionFactoryBeanCustomizers = sqlSessionFactoryBeanCustomizersProvider.getIfAvailable();
}
@Bean
@ConditionalOnMissingBean(DelegatingResourceLoader.class)
public DelegatingResourceLoader delegatingResourceLoader(MavenResourceLoader mavenResourceLoader) {
Map<String, ResourceLoader> loaders = new HashMap<>();
loaders.put("maven", mavenResourceLoader);
return new DelegatingResourceLoader(loaders);
}
public ImageService(ResourceLoader resourceLoader,
ImageRepository imageRepository,
MeterRegistry meterRegistry) {
this.resourceLoader = resourceLoader;
this.imageRepository = imageRepository;
this.meterRegistry = meterRegistry;
}
@PostConstruct
public void initByLookup() {
getBean(BeanFactory.class);
getBean(ApplicationContext.class);
getBean(ResourceLoader.class);
getBean(ApplicationEventPublisher.class);
}
/**
* Test to make sure we can't create a jobs dir resource if the directory can't be created when the input jobs
* dir is invalid in any way.
*
* @throws IOException On error
*/
@Test
void cantGetJobsDirWhenJobsDirInvalid() throws IOException {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final URI jobsDirLocation = URI.create("file:/" + UUID.randomUUID().toString());
final JobsProperties jobsProperties = JobsProperties.getJobsPropertiesDefaults();
jobsProperties.getLocations().setJobs(jobsDirLocation);
final Resource tmpResource = Mockito.mock(Resource.class);
Mockito.when(resourceLoader.getResource(jobsDirLocation.toString())).thenReturn(tmpResource);
Mockito.when(tmpResource.exists()).thenReturn(true);
final File file = Mockito.mock(File.class);
Mockito.when(tmpResource.getFile()).thenReturn(file);
Mockito.when(file.isDirectory()).thenReturn(false);
Assertions
.assertThatIllegalStateException()
.isThrownBy(() -> this.apisAutoConfiguration.jobsDir(resourceLoader, jobsProperties))
.withMessage(jobsDirLocation + " exists but isn't a directory. Unable to continue");
final String localJobsDir = jobsDirLocation + "/";
Mockito.when(file.isDirectory()).thenReturn(true);
final Resource jobsDirResource = Mockito.mock(Resource.class);
Mockito.when(resourceLoader.getResource(localJobsDir)).thenReturn(jobsDirResource);
Mockito.when(tmpResource.exists()).thenReturn(false);
Mockito.when(jobsDirResource.exists()).thenReturn(false);
Mockito.when(jobsDirResource.getFile()).thenReturn(file);
Mockito.when(file.mkdirs()).thenReturn(false);
Assertions
.assertThatIllegalStateException()
.isThrownBy(() -> this.apisAutoConfiguration.jobsDir(resourceLoader, jobsProperties))
.withMessage("Unable to create jobs directory " + jobsDirLocation + " and it doesn't exist.");
}
/**
* 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(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(EnvironmentAware.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.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());
}
}
/**
* Create a new {@link ConfigurationClassParser} instance that will be used
* to populate the set of configuration classes.
*/
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {
this.metadataReaderFactory = metadataReaderFactory;
this.problemReporter = problemReporter;
this.environment = environment;
this.resourceLoader = resourceLoader;
this.registry = registry;
this.componentScanParser = new ComponentScanAnnotationParser(
environment, resourceLoader, componentScanBeanNameGenerator, registry);
this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
public MybatisPlusAutoConfig(MybatisPlusProperties properties, ObjectProvider<Interceptor[]> interceptorsProvider, ResourceLoader resourceLoader, ObjectProvider<DatabaseIdProvider> databaseIdProvider, ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider, ApplicationContext applicationContext) {
this.properties = properties;
this.interceptors = (Interceptor[])interceptorsProvider.getIfAvailable();
this.resourceLoader = resourceLoader;
this.databaseIdProvider = (DatabaseIdProvider)databaseIdProvider.getIfAvailable();
this.configurationCustomizers = (List)configurationCustomizersProvider.getIfAvailable();
this.applicationContext = applicationContext;
}
public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,
@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
this.registry = registry;
this.beanFactory = deduceBeanFactory(registry);
this.environment = (environment != null ? environment : deduceEnvironment(registry));
this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
this.classLoader = deduceClassLoader(resourceLoader, this.beanFactory);
}
@GetMapping("datasource/initialize")
public Result initializeDatasource() {
DataSource dataSource = SpringUtils.getBean(DataSource.class);
ResourceLoader loader = new DefaultResourceLoader();
Resource schema = loader.getResource("classpath:schema.sql");
Resource data = loader.getResource("classpath:data.sql");
ResourceDatabasePopulator populator = new ResourceDatabasePopulator(schema, data);
populator.execute(dataSource);
return Result.success();
}
public ImageService(ResourceLoader resourceLoader,
ImageRepository imageRepository,
MeterRegistry meterRegistry) {
this.resourceLoader = resourceLoader;
this.imageRepository = imageRepository;
this.meterRegistry = meterRegistry;
}
public ImageService(ResourceLoader resourceLoader,
ImageRepository imageRepository,
MeterRegistry meterRegistry) {
this.resourceLoader = resourceLoader;
this.imageRepository = imageRepository;
this.meterRegistry = meterRegistry;
}
@Bean(name = "PhoenixSqlSessionFactory")
@Primary
public SqlSessionFactory phoenixSqlSessionFactory(
@Qualifier("PhoenixDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
ResourceLoader loader = new DefaultResourceLoader();
String resource = "classpath:mybatis-config.xml";
factoryBean.setConfigLocation(loader.getResource(resource));
factoryBean.setSqlSessionFactoryBuilder(new SqlSessionFactoryBuilder());
return factoryBean.getObject();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(DataSource.class)
public JpaVersionsDatabaseInitializer jpaVersionsDatabaseInitializer(DataSource dataSource,
ResourceLoader resourceLoader) {
return new JpaVersionsDatabaseInitializer(dataSource, resourceLoader, this.properties);
}
public ImageService(ResourceLoader resourceLoader,
ImageRepository imageRepository,
MeterRegistry meterRegistry) {
this.resourceLoader = resourceLoader;
this.imageRepository = imageRepository;
this.meterRegistry = meterRegistry;
}
/**
* Create a new {@link ConfigurationClassParser} instance that will be used
* to populate the set of configuration classes.
*/
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {
this.metadataReaderFactory = metadataReaderFactory;
this.problemReporter = problemReporter;
this.environment = environment;
this.resourceLoader = resourceLoader;
this.registry = registry;
this.componentScanParser = new ComponentScanAnnotationParser(
environment, resourceLoader, componentScanBeanNameGenerator, registry);
this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
/**
* Create a new MockPortletContext.
* @param resourceBasePath the WAR root directory (should not end with a slash)
* @param resourceLoader the ResourceLoader to use (or null for the default)
*/
public MockPortletContext(String resourceBasePath, ResourceLoader resourceLoader) {
this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
// Use JVM temp dir as PortletContext temp dir.
String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
if (tempDir != null) {
this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
}
}
/**
* Create a new SpringTemplateLoader.
* @param resourceLoader the Spring ResourceLoader to use
* @param templateLoaderPath the template loader path to use
*/
public SpringTemplateLoader(ResourceLoader resourceLoader, String templateLoaderPath) {
this.resourceLoader = resourceLoader;
if (!templateLoaderPath.endsWith("/")) {
templateLoaderPath += "/";
}
this.templateLoaderPath = templateLoaderPath;
if (logger.isDebugEnabled()) {
logger.debug("SpringTemplateLoader for FreeMarker: using resource loader [" + this.resourceLoader +
"] and template loader path [" + this.templateLoaderPath + "]");
}
}
@Test
@SuppressWarnings("rawtypes")
public void freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
fcfb.setTemplateLoaderPath("file:/mydir");
Properties settings = new Properties();
settings.setProperty("localized_lookup", "false");
fcfb.setFreemarkerSettings(settings);
fcfb.setResourceLoader(new ResourceLoader() {
@Override
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");
}
@Override
public ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
});
fcfb.afterPropertiesSet();
assertThat(fcfb.getObject(), instanceOf(Configuration.class));
Configuration fc = fcfb.getObject();
Template ft = fc.getTemplate("test");
assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}
public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {
this.environment = environment;
this.resourceLoader = resourceLoader;
this.beanNameGenerator = beanNameGenerator;
this.registry = registry;
}
@Before
public void setup() {
cacheManager = new LRUCacheManager(100);
EncryptionComponent encryptionComponent = new EncryptionComponent(null);
ResourceLoader resourceLoader = new DefaultResourceLoader();
//Create Data Manager
dataManager = new DataManager(cacheManager, Collections.emptyList(), null, encryptionComponent, resourceLoader, null);
dataManager.init();
dataManager.resetDeploymentData();
}