org.springframework.core.io.DefaultResourceLoader Java Examples
The following examples show how to use
org.springframework.core.io.DefaultResourceLoader.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BinderFactoryAutoConfigurationTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@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"); }
Example #2
Source File: SimpleStorageProtocolResolverTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@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"); }
Example #3
Source File: StringUtils.java From Shop-for-JavaWeb with MIT License | 6 votes |
/** * 获取工程路径 * @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; }
Example #4
Source File: ImporterComponent.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
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 #5
Source File: SimpleStorageProtocolResolverTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@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(); }
Example #6
Source File: TestDataProviderEngineTest.java From n2o-framework with Apache License 2.0 | 6 votes |
@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("Григорий")); }
Example #7
Source File: ConsoleLog.java From genie with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #8
Source File: ExecutionModeFilterScriptIntegrationTest.java From genie with Apache License 2.0 | 6 votes |
@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 ); }
Example #9
Source File: SeetafaceBuilder.java From seetafaceJNI with BSD 3-Clause "New" or "Revised" License | 6 votes |
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; }
Example #10
Source File: CallbacksSecurityTests.java From spring-analysis-note with MIT License | 6 votes |
@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); }
Example #11
Source File: JobRestControllerIntegrationTest.java From genie with Apache License 2.0 | 6 votes |
@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(); }
Example #12
Source File: ResourceLoaderClassLoadHelper.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void initialize() { if (this.resourceLoader == null) { this.resourceLoader = SchedulerFactoryBean.getConfigTimeResourceLoader(); if (this.resourceLoader == null) { this.resourceLoader = new DefaultResourceLoader(); } } }
Example #13
Source File: TestDataProviderEngineTest.java From n2o-framework with Apache License 2.0 | 5 votes |
@Test public void testCreateWithNumericPK() { TestDataProviderEngine engine = new TestDataProviderEngine(); engine.setResourceLoader(new DefaultResourceLoader()); N2oTestDataProvider provider = new N2oTestDataProvider(); provider.setFile("testNumericPrimaryKey.json"); provider.setOperation(create); Map<String, Object> inParams = new LinkedHashMap<>(); inParams.put("name", "test"); inParams.put("gender.id", 2); inParams.put("gender.name", "Женский"); inParams.put("vip", true); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.setTimeInMillis(0); inParams.put("birthday", c.getTime()); Map result = (Map) engine.invoke(provider, inParams); assertThat(result.get("id"), is(5607776L)); assertThat(result.get("name"), is("test")); assertTrue((Boolean) result.get("vip")); assertThat(((Map) result.get("gender")).get("id"), is(2)); assertThat(((Map) result.get("gender")).get("name"), is("Женский")); assertThat(result.get("birthday"), is(new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(new Date(0)))); //Проверка, что после создания элемент появился в хранилище provider.setOperation(findAll); Map<String, Object> inParamsForRead = new LinkedHashMap<>(); inParamsForRead.put("id", 5607776L); inParamsForRead.put("sorting", new ArrayList<>()); inParamsForRead.put("limit", 1); inParamsForRead.put("offset", 0); inParamsForRead.put("page", 1); inParamsForRead.put("filters", Arrays.asList("id :eq :id")); List<Map> readingResult = (List<Map>) engine.invoke(provider, inParams); assertTrue(readingResult.get(0).equals(result)); }
Example #14
Source File: TestHelper.java From tutorials with MIT License | 5 votes |
private void runScript(String scriptName, DataSource dataSouorce) throws SQLException { DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); Resource script = resourceLoader.getResource(scriptName); try (Connection con = dataSouorce.getConnection()) { ScriptUtils.executeSqlScript(con, script); } }
Example #15
Source File: ClassPathScanningCandidateComponentProviderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void antStylePackageWithScan() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true); provider.setResourceLoader(new DefaultResourceLoader( CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader()))); testAntStyle(provider, ScannedGenericBeanDefinition.class); }
Example #16
Source File: KeystoreFactoryTest.java From spring-boot-security-saml with MIT License | 5 votes |
@Test public void loadKeystore() throws Exception { KeystoreFactory keystoreFactory = new KeystoreFactory(new DefaultResourceLoader()); KeyStore keyStore = keystoreFactory.loadKeystore("classpath:/localhost.cert", "classpath:/localhost.key.der", "alias", "password"); assertThat(keyStore.containsAlias("alias")).isTrue(); assertThat(keyStore.size()).isEqualTo(1); Certificate cert = keyStore.getCertificate("alias"); assertThat(cert.getType()).isEqualTo("X.509"); cert.verify(cert.getPublicKey()); Key key = keyStore.getKey("alias", "password".toCharArray()); assertThat(key.getAlgorithm()).isEqualTo("RSA"); assertThat(key.getFormat()).isEqualTo("PKCS#8"); }
Example #17
Source File: TestDataProviderEngineTest.java From n2o-framework with Apache License 2.0 | 5 votes |
@Test public void testFindOneOperation() { TestDataProviderEngine engine = new TestDataProviderEngine(); engine.setResourceLoader(new DefaultResourceLoader()); N2oTestDataProvider provider = new N2oTestDataProvider(); provider.setFile("testNumericPrimaryKey.json"); provider.setOperation(findOne); Map<String, Object> inParams = new LinkedHashMap<>(); inParams.put("filters", Arrays.asList("id :eq :id")); inParams.put("id", 999); Map result = (Map) engine.invoke(provider, inParams); assertThat(result.get("id"), is(999L)); }
Example #18
Source File: SkipperStreamDeployerTests.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@Test public void testGetStreamStatuses() throws IOException { AppRegistryService appRegistryService = mock(AppRegistryService.class); SkipperClient skipperClient = mock(SkipperClient.class); StreamDefinitionRepository streamDefinitionRepository = mock(StreamDefinitionRepository.class); SkipperStreamDeployer skipperStreamDeployer = new SkipperStreamDeployer(skipperClient, streamDefinitionRepository, appRegistryService, mock(ForkJoinPool.class), new DefaultStreamDefinitionService()); String platformStatus = StreamUtils.copyToString( new DefaultResourceLoader().getResource("classpath:/app-instance-state.json").getInputStream(), Charset.forName("UTF-8")); new DefaultResourceLoader().getResource("classpath:/app-instance-state.json"); Info info = new Info(); Status status = new Status(); status.setStatusCode(StatusCode.DEPLOYED); status.setPlatformStatus(platformStatus); info.setStatus(status); when(skipperClient.status(eq("stream1"))).thenReturn(info); List<AppStatus> appStatues = skipperStreamDeployer.getStreamStatuses("stream1"); assertThat(appStatues).isNotNull(); assertThat(appStatues.size()).isEqualTo(4); }
Example #19
Source File: SpringBootstrap.java From sbp with Apache License 2.0 | 5 votes |
/** * Constructor should be the only thing need to take care for this Class. * Generally new an instance and {@link #run(String...)} it * in {@link SpringBootPlugin#createSpringBootstrap()} method. * * @param primarySources {@link SpringApplication} that annotated with @SpringBootApplication */ @SuppressWarnings("JavadocReference") public SpringBootstrap(SpringBootPlugin plugin, Class<?>... primarySources) { super(new DefaultResourceLoader(plugin.getWrapper().getPluginClassLoader()), primarySources); this.plugin = plugin; this.mainApplicationContext = plugin.getMainApplicationContext(); this.pluginClassLoader = plugin.getWrapper().getPluginClassLoader(); Map<String, Object> presetProperties = ((SpringBootPluginManager) plugin.getWrapper().getPluginManager()).getPresetProperties(); if (presetProperties != null) this.presetProperties.putAll(presetProperties); this.presetProperties.put(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, getExcludeConfigurations()); }
Example #20
Source File: ClassPathScanningCandidateComponentProviderTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void excludeFilterWithIndex() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true); provider.setResourceLoader(new DefaultResourceLoader(TEST_BASE_CLASSLOADER)); provider.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(TEST_BASE_PACKAGE + ".*Named.*"))); testExclude(provider, AnnotatedGenericBeanDefinition.class); }
Example #21
Source File: TestDataProviderEngineTest.java From n2o-framework with Apache License 2.0 | 5 votes |
@Test public void testFindAllAfterChangeInFile() throws IOException { TestDataProviderEngine engine = new TestDataProviderEngine(); engine.setResourceLoader(new DefaultResourceLoader()); engine.setPathOnDisk(testFolder.getRoot() + "/"); N2oTestDataProvider provider = new N2oTestDataProvider(); provider.setFile(testFile.getName()); //Проверка исходных данных в файле List<Map> result = (List<Map>) engine.invoke(provider, new LinkedHashMap<>()); assertThat(result.size(), is(1)); assertThat(result.get(0).get("id"), is(1L)); assertThat(result.get(0).get("name"), is("test1")); assertThat(result.get(0).get("type"), is("1")); //Добавление новых данных FileWriter fileWriter = new FileWriter(testFile); fileWriter.write("[" + "{\"id\":9, \"name\":\"test9\", \"type\":\"9\"}," + "{\"id\":1, \"name\":\"test1\", \"type\":\"1\"}" + "]"); fileWriter.close(); //Проверка, что после изменения json, новые данные будут возвращены result = (List<Map>) engine.invoke(provider, new LinkedHashMap<>()); assertThat(result.size(), is(2)); assertThat(result.get(0).get("id"), is(9L)); assertThat(result.get(0).get("name"), is("test9")); assertThat(result.get(0).get("type"), is("9")); assertThat(result.get(1).get("id"), is(1L)); assertThat(result.get(1).get("name"), is("test1")); assertThat(result.get(1).get("type"), is("1")); }
Example #22
Source File: MockServletContext.java From java-technology-stack with MIT License | 5 votes |
/** * 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, @Nullable 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)); }
Example #23
Source File: TestDataProviderEngineTest.java From n2o-framework with Apache License 2.0 | 5 votes |
@Test public void testCountQuery() { TestDataProviderEngine engine = new TestDataProviderEngine(); engine.setResourceLoader(new DefaultResourceLoader()); N2oTestDataProvider provider = new N2oTestDataProvider(); provider.setFile("testNumericPrimaryKey.json"); provider.setOperation(count); Map<String, Object> inParams = new LinkedHashMap<>(); inParams.put("filters", Collections.emptyList()); Integer result = (Integer) engine.invoke(provider, inParams); assertThat(result, is(151)); }
Example #24
Source File: PluginsConfig.java From nakadi with MIT License | 5 votes |
@Bean @SuppressWarnings("unchecked") public ApplicationService applicationService(@Value("${nakadi.plugins.auth.factory}") final String factoryName, final SystemProperties systemProperties, final DefaultResourceLoader loader) { try { LOGGER.info("Initialize application service factory: " + factoryName); final Class<ApplicationServiceFactory> factoryClass = (Class<ApplicationServiceFactory>) loader.getClassLoader().loadClass(factoryName); final ApplicationServiceFactory factory = factoryClass.newInstance(); return factory.init(systemProperties); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new BeanCreationException("Can't create ApplicationService " + factoryName, e); } }
Example #25
Source File: DefaultPersistenceUnitManagerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void defaultDomainWithScan() { this.manager.setPackagesToScan("org.springframework.orm.jpa.domain"); this.manager.setResourceLoader(new DefaultResourceLoader( CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader()))); testDefaultDomain(); }
Example #26
Source File: JobDependencies.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@Bean @ConditionalOnMissingBean public AppRegistryService appRegistryService(AppRegistrationRepository appRegistrationRepository, AuditRecordService auditRecordService) { return new DefaultAppRegistryService(appRegistrationRepository, new AppResourceCommon(new MavenProperties(), new DefaultResourceLoader()), auditRecordService); }
Example #27
Source File: DefaultPersistenceUnitManagerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void defaultDomainWithIndex() { this.manager.setPackagesToScan("org.springframework.orm.jpa.domain"); this.manager.setResourceLoader(new DefaultResourceLoader( CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), new ClassPathResource("spring.components", Person.class)))); testDefaultDomain(); }
Example #28
Source File: WebSecurityConfig.java From spring-tsers-auth with Apache License 2.0 | 5 votes |
@Bean @Qualifier("idp-ssocircle") public ExtendedMetadataDelegate ssoCircleExtendedMetadataProvider() throws MetadataProviderException { AbstractMetadataProvider provider = new AbstractMetadataProvider() { @Override protected XMLObject doGetMetadata() throws MetadataProviderException { DefaultResourceLoader loader = new DefaultResourceLoader(); Resource storeFile = loader.getResource("classPath:/saml/idp-metadata.xml"); ParserPool parser = parserPool(); try { Document mdDocument = parser.parse(storeFile.getInputStream()); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(mdDocument.getDocumentElement()); return unmarshaller.unmarshall(mdDocument.getDocumentElement()); } catch (Exception e) { e.printStackTrace(); throw new MetadataProviderException(); } } }; ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(provider, extendedMetadata()); extendedMetadataDelegate.setMetadataTrustCheck(false); extendedMetadataDelegate.setMetadataRequireSignature(false); return extendedMetadataDelegate; }
Example #29
Source File: TestDataProviderEngineTest.java From n2o-framework with Apache License 2.0 | 5 votes |
@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)); }
Example #30
Source File: S3StoreFactoryBean.java From spring-content with Apache License 2.0 | 5 votes |
@Override protected Object getContentStoreImpl() { SimpleStorageProtocolResolver s3Protocol = new SimpleStorageProtocolResolver(client); s3Protocol.afterPropertiesSet(); DefaultResourceLoader loader = new DefaultResourceLoader(); loader.addProtocolResolver(s3Protocol); return new DefaultS3StoreImpl(loader, s3StorePlacementService, client); }