下面列出了怎么用org.springframework.core.io.DefaultResourceLoader的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 获取工程路径
* @return
*/
public static String getProjectPath(){
String projectPath = "";
try {
File file = new DefaultResourceLoader().getResource("").getFile();
if (file != null){
while(true){
File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
if (f == null || f.exists()){
break;
}
if (file.getParentFile() != null){
file = file.getParentFile();
}else{
break;
}
}
projectPath = file.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return projectPath;
}
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);
}
}
@Test
void testGetResourceWithVersionId() {
AmazonS3 amazonS3 = mock(AmazonS3.class);
SimpleStorageProtocolResolver resourceLoader = new SimpleStorageProtocolResolver(
amazonS3);
ObjectMetadata metadata = new ObjectMetadata();
when(amazonS3.getObjectMetadata(any(GetObjectMetadataRequest.class)))
.thenReturn(metadata);
String resourceName = "s3://bucket/object^versionIdValue";
Resource resource = resourceLoader.resolve(resourceName,
new DefaultResourceLoader());
assertThat(resource).isNotNull();
}
/**
* Load and print the Spring banner (if one is configured) to UserConsole.
*
* @param environment the Spring environment
*/
public static void printBanner(final Environment environment) {
try {
final String bannerLocation = environment.getProperty(BANNER_LOCATION_SPRING_PROPERTY_KEY);
if (StringUtils.isNotBlank(bannerLocation)) {
final ResourceLoader resourceLoader = new DefaultResourceLoader();
final Resource resource = resourceLoader.getResource(bannerLocation);
if (resource.exists()) {
final String banner = StreamUtils.copyToString(
resource.getInputStream(),
environment.getProperty(
BANNER_CHARSET_SPRING_PROPERTY_KEY,
Charset.class,
StandardCharsets.UTF_8
)
);
ConsoleLog.getLogger().info(banner);
}
}
} catch (final Throwable t) {
log.error("Failed to print banner", t);
}
}
@SuppressWarnings("rawtypes")
@Test
public void loadBinderTypeRegistryWithSharedEnvironmentAndServletWebApplicationType()
throws Exception {
String[] properties = new String[] {"binder1.name=foo", "spring.main.web-application-type=SERVLET"};
ClassLoader classLoader = createClassLoader(new String[] { "binder1" },
properties);
ConfigurableApplicationContext context = new SpringApplicationBuilder(SimpleApplication.class, ServletWebServerFactoryAutoConfiguration.class)
.resourceLoader(new DefaultResourceLoader(classLoader))
.properties(properties).web(WebApplicationType.SERVLET).run();
BinderFactory binderFactory = context.getBean(BinderFactory.class);
Binder binder1 = binderFactory.getBinder("binder1", MessageChannel.class);
assertThat(binder1).hasFieldOrPropertyWithValue("name", "foo");
}
@BeforeEach
void beforeJobs() throws Exception {
this.schedulerJobName = UUID.randomUUID().toString();
this.schedulerRunId = UUID.randomUUID().toString();
this.metadata = GenieObjectMapper.getMapper().readTree(
"{\""
+ SCHEDULER_JOB_NAME_KEY
+ "\":\""
+ this.schedulerJobName
+ "\", \""
+ SCHEDULER_RUN_ID_KEY
+ "\":\""
+ this.schedulerRunId
+ "\"}"
);
this.resourceLoader = new DefaultResourceLoader();
this.createAnApplication(APP1_ID, APP1_NAME);
this.createAnApplication(APP2_ID, APP2_NAME);
this.createAllClusters();
this.createAllCommands();
this.linkAllEntities();
}
@Before
public void setUp() throws Exception {
final ProtectionDomain empty = new ProtectionDomain(null,
new Permissions());
provider = new SecurityContextProvider() {
private final AccessControlContext acc = new AccessControlContext(
new ProtectionDomain[] { empty });
@Override
public AccessControlContext getAccessControlContext() {
return acc;
}
};
DefaultResourceLoader drl = new DefaultResourceLoader();
Resource config = drl
.getResource("/org/springframework/beans/factory/support/security/callbacks.xml");
beanFactory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(config);
beanFactory.setSecurityContextProvider(provider);
}
private static Properties getConfig() {
Properties properties = new Properties();
String location = "classpath:/seetaface.properties";
InputStream is = null;
try {
is = new DefaultResourceLoader().getResource(location).getInputStream();
properties.load(is);
logger.debug("seetaface config: {}", properties.toString());
} catch (IOException ex) {
logger.error("Could not load property file:" + location, ex);
}finally {
try {
if (null != is){
is.close();
}
}catch (Exception e){
}
}
return properties;
}
@BeforeEach
void setUp() {
final MeterRegistry meterRegistry = new SimpleMeterRegistry();
final ScriptManagerProperties scriptManagerProperties = new ScriptManagerProperties();
final TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
final ExecutorService executorService = Executors.newCachedThreadPool();
final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
final ResourceLoader resourceLoader = new DefaultResourceLoader();
final ObjectMapper objectMapper = GenieObjectMapper.getMapper();
final ScriptManager scriptManager = new ScriptManager(
scriptManagerProperties,
taskScheduler,
executorService,
scriptEngineManager,
resourceLoader,
meterRegistry
);
this.scriptProperties = new ExecutionModeFilterScriptProperties();
this.executionModeFilterScript = new ExecutionModeFilterScript(
scriptManager,
scriptProperties,
objectMapper,
meterRegistry
);
}
@Test
public void testPagination() {
TestDataProviderEngine engine = new TestDataProviderEngine();
engine.setResourceLoader(new DefaultResourceLoader());
N2oTestDataProvider provider = new N2oTestDataProvider();
provider.setFile("testNumericPrimaryKey.json");
provider.setOperation(findAll);
Map<String, Object> inParams = new LinkedHashMap<>();
inParams.put("sorting", new ArrayList<>());
inParams.put("limit", 10);
inParams.put("offset", 10);
inParams.put("page", 2);
List<Map> result = (List<Map>) engine.invoke(provider, inParams);
assertThat(result.size(), is(10));
assertThat(result.get(0).get("id"), is(5607635L));
assertThat(result.get(0).get("name"), is("Адилхан"));
assertThat(result.get(9).get("id"), is(5607644L));
assertThat(result.get(9).get("name"), is("Григорий"));
}
@Test
void testGetResourceWithMalFormedUrl() {
AmazonS3 amazonS3 = mock(AmazonS3.class);
DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
resourceLoader.addProtocolResolver(new SimpleStorageProtocolResolver(amazonS3));
try {
assertThat(resourceLoader.getResource("s3://bucketsAndObject")).isNotNull();
fail("expected exception due to missing object");
}
catch (IllegalArgumentException e) {
assertThat(e.getMessage().contains("valid bucket name")).isTrue();
}
verify(amazonS3, times(0)).getObjectMetadata("bucket", "object");
}
private X509Certificate retriveRootX509Certificate(String rootCertificateClassPath){
try{
ResourceLoader resourceLoader = new DefaultResourceLoader();
return cryptoCommon.generateX509FromInputStream(resourceLoader
.getResource(rootCertificateClassPath)
.getInputStream());
} catch (IOException ex) {
ex.printStackTrace();
Logger.getLogger(MDSUrlService.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalArgumentException(ex);
}
}
@Bean
public KeyManager keyManager() {
DefaultResourceLoader loader = new DefaultResourceLoader();
Resource storeFile = loader
.getResource("classpath:/saml/samlKeystore.jks");
String storePass = "nalle123";
Map<String, String> passwords = new HashMap<String, String>();
passwords.put("apollo", "nalle123");
String defaultKey = "apollo";
return new JKSKeyManager(storeFile, storePass, passwords, defaultKey);
}
private static TemplateLoader mustacheTemplateLoader(String prefix) {
ResourceLoader resourceLoader = new DefaultResourceLoader();
return (name) -> {
String location = prefix + name + ".mustache";
return new InputStreamReader(resourceLoader.getResource(location).getInputStream(), StandardCharsets.UTF_8);
};
}
/**
* @return returns an array of validated Resources for use with overlaid property files
*/
public Resource[] constructResourceList() {
String configHost = System.getProperties().getProperty(DEFAULT_CONFIG_HOST_PROPERTY);
if (configHost == null) {
log("No config Host defined - assuming " + DEFAULT_CONFIG_HOST_PROPERTY_VALUE);
configHost = DEFAULT_CONFIG_HOST_PROPERTY_VALUE;
}
DefaultResourceLoader loader = new DefaultResourceLoader();
Resource configOverrideResource = loader.getResource(configHost + configOverride);
return handleConfig(defaultConfig, appProperties, configOverrideResource);
}
@Test
public void antStylePackageWithScan() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.setResourceLoader(new DefaultResourceLoader(
CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader())));
testAntStyle(provider, ScannedGenericBeanDefinition.class);
}
@Test
public void testRootControllerResponse() throws Exception {
String mvcResult = mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String expectedResult = StreamUtils.copyToString(
new DefaultResourceLoader().getResource("classpath:/root-controller-result.json").getInputStream(),
StandardCharsets.UTF_8);
Assert.assertEquals(expectedResult.replace("\n", ""), mvcResult);
}
@Test
public void bogusPackageWithIndex() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.setResourceLoader(new DefaultResourceLoader(TEST_BASE_CLASSLOADER));
Set<BeanDefinition> candidates = provider.findCandidateComponents("bogus");
assertEquals(0, candidates.size());
}
/**
* Create a new {@code MockServletContext} using the supplied resource base
* path and resource loader.
* <p>Registers a {@link MockRequestDispatcher} for the Servlet named
* {@literal 'default'}.
* @param resourceBasePath the root directory of the WAR (should not end with a slash)
* @param resourceLoader the ResourceLoader to use (or null for the default)
* @see #registerNamedDispatcher
*/
public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
this.resourceBasePath = resourceBasePath;
// Use JVM temp dir as ServletContext temp dir.
String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
if (tempDir != null) {
this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
}
registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName));
}
@Override
public void afterPropertiesSet() throws Exception {
Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()).getResources(mapperLocations);
String group = "default";
MybatisMapperParser.addMapperLocations(group,resources);
MybatisConfigs.addProperties(group, properties.getProperties());
JeesuiteMybatisRegistry.register(group,sqlSessionFactory.getConfiguration());
}
/**
* 获取工程路径
*
* @return
*/
public static String getProjectPath(String fileName, String relativeUiPath) {
String projectPath = "";
try {
File file = new DefaultResourceLoader().getResource("").getFile();
if (file != null) {
while (true) {
File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
if (f == null || f.exists()) {
break;
}
if (file.getParentFile() != null) {
file = file.getParentFile();
} else {
break;
}
}
if (!fileName.endsWith(DOT_JAVA) && isNotEmpty(relativeUiPath)) {
File fileTemp = new File(file.getPath() + File.separator + relativeUiPath);
if (fileTemp == null || fileTemp.exists()) {
file = fileTemp;
}
}
projectPath = file.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return projectPath;
}
@Test
public void customSupportIncludeFilterWithNonIndexedTypeUseScan() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.setResourceLoader(new DefaultResourceLoader(TEST_BASE_CLASSLOADER));
// This annotation type is not directly annotated with Indexed so we can use
// the index to find candidates
provider.addIncludeFilter(new AnnotationTypeFilter(CustomStereotype.class));
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
assertTrue(containsBeanClass(candidates, DefaultNamedComponent.class));
assertEquals(1, candidates.size());
assertBeanDefinitionType(candidates, ScannedGenericBeanDefinition.class);
}
@Test
public void excludeFilterWithScan() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.setResourceLoader(new DefaultResourceLoader(
CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader())));
provider.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(TEST_BASE_PACKAGE + ".*Named.*")));
testExclude(provider, ScannedGenericBeanDefinition.class);
}
@Test
public void shouldPerformSchemaUpgrade() throws IOException {
try (CloseableJsonDB jsondb = MemorySqlJsonDB.create(Collections.emptyList());
InputStream data = UpgradeVersion41Test.class.getResourceAsStream("/migrations/41/integration.json")) {
jsondb.push("/integrations", data);
final Migrator migrator = new DefaultMigrator(new DefaultResourceLoader());
migrator.migrate(jsondb, 41);
final List<Integration> integrations = load(jsondb, "/integrations", Integration.class);
// integrations
assertThat(integrations).hasSize(1);
final Integration integration = integrations.get(0);
assertThat(integration.getFlows()).hasSize(1);
final Flow flow = integration.getFlows().get(0);
final List<Step> steps = flow.getSteps();
assertThat(steps).hasSize(2);
Step maybeStep = steps.get(1);
assertThat(maybeStep.getAction()).isPresent().satisfies(action -> assertThat(action.get().getId()).contains("io.syndesis:fhir-read-connector"));
final Optional<Connection> maybeConnection = maybeStep.getConnection();
assertThat(maybeConnection).isPresent().satisfies(connection -> assertThat(connection.get().getConnector()).isPresent()
.satisfies(connector -> assertThat(connector.get().getConfiguredProperties()).containsEntry("encoding", "XML")));
}
}
private GetDataResponse testQuery(String path,
ReadCompileTerminalPipeline<ReadCompileBindTerminalPipeline> pipeline,
Map<String, String[]> params) {
N2oInvocationFactory invocationFactory = Mockito.mock(N2oInvocationFactory.class);
TestDataProviderEngine testDataProviderEngine = new TestDataProviderEngine();
testDataProviderEngine.setResourceLoader(new DefaultResourceLoader());
Mockito.when(invocationFactory.produce(Mockito.any(Class.class))).thenReturn(testDataProviderEngine);
ContextEngine contextEngine = Mockito.mock(ContextEngine.class);
UserContext userContext = new UserContext(contextEngine);
ContextProcessor contextProcessor = new ContextProcessor(userContext);
N2oQueryProcessor queryProcessor = new N2oQueryProcessor(invocationFactory, new N2oQueryExceptionHandler());
N2oEnvironment env = new N2oEnvironment();
env.setContextProcessor(contextProcessor);
queryProcessor.setEnvironment(env);
N2oSubModelsProcessor subModelsProcessor = Mockito.mock(N2oSubModelsProcessor.class);
Mockito.doNothing().when(subModelsProcessor);
DataProcessingStack dataProcessingStack = Mockito.mock(SpringDataProcessingStack.class);
SimpleDefaultValuesController valuesController = new SimpleDefaultValuesController(dataProcessingStack, queryProcessor,
subModelsProcessor, null, null);
Map<String, Object> map = new HashMap<>();
map.put("SimpleDefaultValuesController", valuesController);
N2oRouter router = new N2oRouter(builder.getEnvironment(), pipeline);
N2oControllerFactory factory = new N2oControllerFactory(map);
factory.setEnvironment(builder.getEnvironment());
DataController controller = new DataController(factory, builder.getEnvironment(), router);
return controller.getData(path, params, userContext);
}
@Test
public void testSorting() {
TestDataProviderEngine engine = new TestDataProviderEngine();
engine.setResourceLoader(new DefaultResourceLoader());
N2oTestDataProvider provider = new N2oTestDataProvider();
provider.setFile("testNumericPrimaryKey.json");
//Сортировка по возрастанию по строковому полю
Map<String, Object> inParams = new LinkedHashMap<>();
inParams.put("sorting", Arrays.asList("name :nameDirection"));
inParams.put("nameDirection", "asc");
inParams.put("limit", 10);
inParams.put("offset", 0);
inParams.put("page", 1);
List<Map> result = (List<Map>) engine.invoke(provider, inParams);
assertThat(result.size(), is(10));
assertThat(result.get(0).get("id"), is(999L));
assertThat(result.get(9).get("id"), is(5607771L));
//Сортировка по убыванию по числовому полю
inParams.put("sorting", Arrays.asList("id :idDirection"));
inParams.put("idDirection", "desc");
result = (List<Map>) engine.invoke(provider, inParams);
assertThat(result.get(0).get("id"), is(5607775L));
assertThat(result.get(9).get("id"), is(5607766L));
}
/**
* Create a new CachingMetadataReaderFactory for the given {@link ResourceLoader},
* using a shared resource cache if supported or a local resource cache otherwise.
* @param resourceLoader the Spring ResourceLoader to use
* (also determines the ClassLoader to use)
* @see DefaultResourceLoader#getResourceCache
*/
public CachingMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
super(resourceLoader);
if (resourceLoader instanceof DefaultResourceLoader) {
this.metadataReaderCache =
((DefaultResourceLoader) resourceLoader).getResourceCache(MetadataReader.class);
}
else {
setCacheLimit(DEFAULT_CACHE_LIMIT);
}
}
@Test
public void testDeleteWithStringPK() {
TestDataProviderEngine engine = new TestDataProviderEngine();
engine.setResourceLoader(new DefaultResourceLoader());
N2oTestDataProvider provider = new N2oTestDataProvider();
provider.setFile("testStringPrimaryKey.json");
provider.setOperation(findAll);
provider.setPrimaryKeyType(string);
provider.setPrimaryKey("testId");
Map<String, Object> inParamsForRead = new LinkedHashMap<>();
inParamsForRead.put("sorting", new ArrayList<>());
inParamsForRead.put("limit", 151);
inParamsForRead.put("offset", 0);
inParamsForRead.put("page", 1);
//Проверка, что до удаления элемент существует
List<Map> result = (List<Map>) engine.invoke(provider, inParamsForRead);
result = result.stream().filter(map -> map.get("testId").equals("a7e0973e-5dfc-4f77-8e1b-2c284d70453d")).collect(Collectors.toList());
assertThat(result.size(), is(1));
Map<String, Object> inParamsForDelete = new LinkedHashMap<>();
inParamsForDelete.put("testId", "a7e0973e-5dfc-4f77-8e1b-2c284d70453d");
provider.setOperation(delete);
engine.invoke(provider, inParamsForDelete);
//Проверка, что удаление прошло успешно
provider.setOperation(null);
result = (List<Map>) engine.invoke(provider, inParamsForRead);
result = result.stream().filter(map -> map.get("testId").equals("a7e0973e-5dfc-4f77-8e1b-2c284d70453d")).collect(Collectors.toList());
assertThat(result.size(), is(0));
}
static Resource getResource(String location) {
if (isExistingFile(location)) {
return new FileSystemResource(location);
} else {
ResourceLoader loader = new DefaultResourceLoader();
return loader.getResource(location);
}
}
@Test
public void testDeleteWithNumericPK() {
TestDataProviderEngine engine = new TestDataProviderEngine();
engine.setResourceLoader(new DefaultResourceLoader());
N2oTestDataProvider provider = new N2oTestDataProvider();
Map<String, Object> inParamsForRead = new LinkedHashMap<>();
provider.setFile("testNumericPrimaryKey.json");
provider.setOperation(findAll);
inParamsForRead.put("sorting", new ArrayList<>());
inParamsForRead.put("limit", 151);
inParamsForRead.put("offset", 0);
inParamsForRead.put("page", 1);
//Проверка, что до удаления элемент существует
List<Map> result = (List<Map>) engine.invoke(provider, inParamsForRead);
result = result.stream().filter(map -> map.get("id").equals(5607676L)).collect(Collectors.toList());
assertThat(result.size(), is(1));
Map<String, Object> inParamsForDelete = new LinkedHashMap<>();
inParamsForDelete.put("id", 5607676);
provider.setOperation(delete);
engine.invoke(provider, inParamsForDelete);
//Проверка, что удаление прошло успешно
provider.setOperation(null);
result = (List<Map>) engine.invoke(provider, inParamsForRead);
result = result.stream().filter(map -> map.get("id").equals(5607676)).collect(Collectors.toList());
assertThat(result.size(), is(0));
}