org.springframework.core.io.Resource Java Examples
The following examples show how to use
org.springframework.core.io.Resource.
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: PropertiesConfiguration.java From gravitee-management-rest-api with Apache License 2.0 | 7 votes |
@Bean(name = "graviteeProperties") public static Properties graviteeProperties() throws IOException { LOGGER.info("Loading Gravitee Management configuration."); YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); String yamlConfiguration = System.getProperty(GRAVITEE_CONFIGURATION); Resource yamlResource = new FileSystemResource(yamlConfiguration); LOGGER.info("\tGravitee Management configuration loaded from {}", yamlResource.getURL().getPath()); yaml.setResources(yamlResource); Properties properties = yaml.getObject(); LOGGER.info("Loading Gravitee Management configuration. DONE"); return properties; }
Example #2
Source File: SingleResourceAutoDeploymentStrategy.java From flowable-engine with Apache License 2.0 | 6 votes |
@Override protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, ProcessEngine engine) { // Create a separate deployment for each resource using the resource name RepositoryService repositoryService = engine.getRepositoryService(); for (final Resource resource : resources) { final String resourceName = determineResourceName(resource); final DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(resourceName); addResource(resource, resourceName, deploymentBuilder); try { deploymentBuilder.deploy(); } catch (RuntimeException e) { if (isThrowExceptionOnDeploymentFailure()) { throw e; } else { LOGGER.warn( "Exception while autodeploying process definitions for resource {}. This exception can be ignored if the root cause indicates a unique constraint violation, which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", resource, e); } } } }
Example #3
Source File: CROSSRecSimilarityCalculatorTest.java From scava with Eclipse Public License 2.0 | 6 votes |
@Before public void init(){ artifactRepository.deleteAll(); githubUserRepository.deleteAll(); crossRecGraphRepository.deleteAll(); try { ObjectMapper mapper = new ObjectMapper(); Resource resource = new ClassPathResource("artifacts.json"); InputStream resourceInputStream = resource.getInputStream(); artifacts = mapper.readValue(resourceInputStream, new TypeReference<List<Artifact>>(){}); artifactRepository.save(artifacts); for (Artifact artifact : artifacts) { ossmeterImporter.storeGithubUser(artifact.getStarred(), artifact.getFullName()); ossmeterImporter.storeGithubUserCommitter(artifact.getCommitteers(), artifact.getFullName()); } resourceInputStream.close(); } catch (IOException e) { logger.error(e.getMessage()); } }
Example #4
Source File: CamundaBpmRunProcessEngineConfiguration.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
@Override protected String getFileResourceName(Resource resource) { // only path relative to the root deployment directory as identifier to // prevent re-deployments when the path changes (e.g. distro is moved) try { String deploymentDir = env.getProperty(CamundaBpmRunDeploymentConfiguration.CAMUNDA_DEPLOYMENT_DIR_PROPERTY); if(File.separator.equals("\\")) { deploymentDir = deploymentDir.replace("\\", "/"); } String resourceAbsolutePath = resource.getURI().toString(); int startIndex = resourceAbsolutePath.indexOf(deploymentDir) + deploymentDir.length(); return resourceAbsolutePath.substring(startIndex); } catch (IOException e) { throw new ProcessEngineException("Failed to locate resource " + resource.getFilename(), e); } }
Example #5
Source File: MockZisTest.java From secure-data-service with Apache License 2.0 | 6 votes |
@Test public void shouldRegisterAgents() throws IOException { Resource xmlFile = new ClassPathResource("TestRegisterMessage.xml"); StringWriter writer = new StringWriter(); IOUtils.copy(xmlFile.getInputStream(), writer, "UTF-8"); String sifString = writer.toString(); mockZis.parseSIFMessage(sifString); //check that the correct URL has been added to the Set<String> agentUrls = mockZis.getAgentUrls(); Assert.assertEquals("Should register one agent", 1, agentUrls.size()); Assert.assertEquals("Registered agent URL incorrect", "http://10.81.1.35:25101/zone/TestZone/", agentUrls.iterator().next()); }
Example #6
Source File: SqlSessionFactory2Config.java From mybatis.flying with Apache License 2.0 | 6 votes |
@Bean(name = "sqlSessionFactory2") @Primary public SqlSessionFactoryBean createSqlSessionFactory2Bean() throws IOException { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); /** 设置datasource */ sqlSessionFactoryBean.setDataSource(dataSource2); VFS.addImplClass(SpringBootVFS.class); /** 设置mybatis configuration 扫描路径 */ sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("Configuration.xml")); /** 设置typeAlias 包扫描路径 */ sqlSessionFactoryBean.setTypeAliasesPackage("indi.mybatis.flying"); /** 添加mapper 扫描路径 */ PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] ra1 = resolver.getResources("classpath*:indi/mybatis/flying/mapper*/*.xml"); sqlSessionFactoryBean.setMapperLocations(ra1); // 扫描映射文件 return sqlSessionFactoryBean; }
Example #7
Source File: ResourceServerTokenServicesConfiguration.java From spring-security-oauth2-boot with Apache License 2.0 | 6 votes |
@Bean @ConditionalOnMissingBean(JwtAccessTokenConverter.class) public JwtAccessTokenConverter accessTokenConverter() { Assert.notNull(this.resource.getJwt().getKeyStore(), "keyStore cannot be null"); Assert.notNull(this.resource.getJwt().getKeyStorePassword(), "keyStorePassword cannot be null"); Assert.notNull(this.resource.getJwt().getKeyAlias(), "keyAlias cannot be null"); JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); Resource keyStore = this.context.getResource(this.resource.getJwt().getKeyStore()); char[] keyStorePassword = this.resource.getJwt().getKeyStorePassword().toCharArray(); KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keyStore, keyStorePassword); String keyAlias = this.resource.getJwt().getKeyAlias(); char[] keyPassword = Optional.ofNullable(this.resource.getJwt().getKeyPassword()).map(String::toCharArray) .orElse(keyStorePassword); converter.setKeyPair(keyStoreKeyFactory.getKeyPair(keyAlias, keyPassword)); return converter; }
Example #8
Source File: JourneySimulator.java From istio-fleetman with MIT License | 6 votes |
/** * Read the data from the resources directory - should work for an executable Jar as * well as through direct execution */ @PostConstruct private void setUpData() { PathMatchingResourcePatternResolver path = new PathMatchingResourcePatternResolver(); try { for (Resource nextFile : path.getResources("tracks/*")) { URL resource = nextFile.getURL(); File f = new File(resource.getFile()); String vehicleName = VehicleNameUtils.prettifyName(f.getName()); vehicleNames.add(vehicleName); populateReportQueueForVehicle(vehicleName); } } catch (IOException e) { throw new RuntimeException(e); } positionTracker.clearHistories(); }
Example #9
Source File: SQLErrorCodesFactoryTests.java From java-technology-stack with MIT License | 6 votes |
/** * Check that user defined error codes take precedence. */ @Test public void testFindUserDefinedCodes() { class TestSQLErrorCodesFactory extends SQLErrorCodesFactory { @Override protected Resource loadResource(String path) { if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) { return new ClassPathResource("test-error-codes.xml", SQLErrorCodesFactoryTests.class); } return null; } } // Should have loaded without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0); assertEquals(2, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length); assertEquals("1", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[0]); assertEquals("2", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]); }
Example #10
Source File: SingleResourceAutoDeploymentStrategyTest.java From activiti6-boot2 with Apache License 2.0 | 6 votes |
@Test public void testDeployResources() { final Resource[] resources = new Resource[] { resourceMock1, resourceMock2, resourceMock3, resourceMock4, resourceMock5 }; classUnderTest.deployResources(deploymentNameHint, resources, repositoryServiceMock); verify(repositoryServiceMock, times(5)).createDeployment(); verify(deploymentBuilderMock, times(5)).enableDuplicateFiltering(); verify(deploymentBuilderMock, times(1)).name(resourceName1); verify(deploymentBuilderMock, times(1)).name(resourceName2); verify(deploymentBuilderMock, times(1)).name(resourceName3); verify(deploymentBuilderMock, times(1)).name(resourceName4); verify(deploymentBuilderMock, times(1)).name(resourceName5); verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName1), isA(InputStream.class)); verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName2), isA(InputStream.class)); verify(deploymentBuilderMock, times(3)).addZipInputStream(isA(ZipInputStream.class)); verify(deploymentBuilderMock, times(5)).deploy(); }
Example #11
Source File: MockServletContext.java From java-technology-stack with MIT License | 6 votes |
@Override @Nullable public InputStream getResourceAsStream(String path) { Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); if (!resource.exists()) { return null; } try { return resource.getInputStream(); } catch (IOException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not open InputStream for " + resource, ex); } return null; } }
Example #12
Source File: WebJarResourceResolver.java From cuba with Apache License 2.0 | 6 votes |
protected void scanResources(ApplicationContext applicationContext) throws IOException { // retrieve all resources from all JARs Resource[] resources = applicationContext.getResources("classpath*:META-INF/resources/webjars/**"); for (Resource resource : resources) { URL url = resource.getURL(); String urlString = url.toString(); int classPathStartIndex = urlString.indexOf(CLASSPATH_WEBJAR_PREFIX); if (classPathStartIndex > 0) { String resourcePath = urlString.substring(classPathStartIndex + CLASSPATH_WEBJAR_PREFIX.length()); if (!Strings.isNullOrEmpty(resourcePath) && !resourcePath.endsWith("/")) { mapping.put(resourcePath, new UrlHolder(url)); } } else { log.debug("Ignored WebJAR resource {} since it does not contain class path prefix {}", urlString, CLASSPATH_WEBJAR_PREFIX); } } this.fullPathIndex = getFullPathIndex(mapping.keySet()); }
Example #13
Source File: JsonCacheDataImporterExporterIntegrationTests.java From spring-boot-data-geode with Apache License 2.0 | 6 votes |
@Bean JsonCacheDataImporterExporter exampleRegionDataImporter() { return new JsonCacheDataImporterExporter() { @Override @SuppressWarnings("rawtypes") protected Optional<Resource> getResource(@NonNull Region region, String resourcePrefix) { return Optional.ofNullable(resourceSupplier.get()); } @NonNull @Override Writer newWriter(@NonNull Resource resource) { return writerSupplier.get(); } }; }
Example #14
Source File: PopulatorConfig.java From sdn-rx with Apache License 2.0 | 5 votes |
@Bean public FactoryBean<ResourceReaderRepositoryPopulator> respositoryPopulator( ObjectMapper objectMapper, // <1> ResourceLoader resourceLoader) { Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean(); factory.setMapper(objectMapper); factory.setResources(new Resource[] { resourceLoader.getResource("classpath:data.json") }); // <2> return factory; }
Example #15
Source File: StoreRestController.java From spring-content with Apache License 2.0 | 5 votes |
protected void handleUpdate(HttpHeaders headers, String store, String path, InputStream content) throws IOException { ContentStoreInfo info = ContentStoreUtils.findStore(storeService, store); if (info == null) { throw new IllegalArgumentException("Not a Store"); } String pathToUse = path.substring(store.length() + 1); Resource r = ((Store) info.getImpementation()).getResource(pathToUse); if (r == null) { throw new ResourceNotFoundException(); } if (r instanceof WritableResource == false) { throw new UnsupportedOperationException(); } if (r.exists()) { HeaderUtils.evaluateHeaderConditions(headers, null, new Date(r.lastModified())); } InputStream in = content; OutputStream out = ((WritableResource) r).getOutputStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); }
Example #16
Source File: LanguageServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
/** * Construct language service. * @param config property file with i18n configurations * @param shopService shop service */ public LanguageServiceImpl(final Resource config, final ShopService shopService) throws IOException { final Properties properties = new Properties(); properties.load(config.getInputStream()); this.shopService = shopService; this.languageName = new TreeMap<>((o1, o2) -> o1.compareTo(o2)); this.languageName.putAll(getLanguageNameFromConfig(properties)); this.shopToLanguageMap = getShopToLanguageMapFromConfig(properties); this.supportedLanguages = this.shopToLanguageMap.get("DEFAULT"); }
Example #17
Source File: ResourceDecoderTests.java From java-technology-stack with MIT License | 5 votes |
@Override protected void testDecodeError(Publisher<DataBuffer> input, ResolvableType outputType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { input = Flux.concat( Flux.from(input).take(1), Flux.error(new InputException())); Flux<Resource> result = this.decoder.decode(input, outputType, mimeType, hints); StepVerifier.create(result) .expectError(InputException.class) .verify(); }
Example #18
Source File: Sys.java From zfile with MIT License | 5 votes |
public Sys() { this.osName = System.getProperty("os.name"); this.osArch = System.getProperty("os.arch"); this.osVersion = System.getProperty("os.version"); Resource resource = new ClassPathResource(""); try { this.projectDir = resource.getFile().getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } long uptime = ManagementFactory.getRuntimeMXBean().getUptime(); this.upTime = DateUtil.formatBetween(uptime, BetweenFormater.Level.SECOND); }
Example #19
Source File: ColumnDetectorXmlDataSetLoader.java From gazpachoquest with GNU General Public License v3.0 | 5 votes |
@Override protected IDataSet createDataSet(Resource resource) throws Exception { FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder(); builder.setColumnSensing(true); InputStream inputStream = resource.getInputStream(); try { return builder.build(inputStream); } finally { inputStream.close(); } }
Example #20
Source File: InterchangeStudentEnrollmentTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testGraduationPlan() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentEnrollment.xsd"); Resource inputXml = new ClassPathResource("parser/InterchangeStudentEnrollment/GraduationPlan.xml"); Resource expectedJson = new ClassPathResource("parser/InterchangeStudentEnrollment/GraduationPlan.json"); EntityTestHelper.parseAndVerify(schema, inputXml, expectedJson); }
Example #21
Source File: SingleResourceAutoDeploymentStrategyTest.java From flowable-engine with Apache License 2.0 | 5 votes |
@Test public void testDeployResources() { final Resource[] resources = new Resource[] { resourceMock1, resourceMock2, resourceMock3 }; classUnderTest.deployResources(deploymentNameHint, resources, formEngineMock); verify(repositoryServiceMock, times(3)).createDeployment(); verify(deploymentBuilderMock, times(3)).enableDuplicateFiltering(); verify(deploymentBuilderMock, times(1)).name(resourceName1); verify(deploymentBuilderMock, times(1)).name(resourceName2); verify(deploymentBuilderMock, times(1)).name(resourceName3); verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName1), isA(InputStream.class)); verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName2), isA(InputStream.class)); verify(deploymentBuilderMock, times(3)).deploy(); }
Example #22
Source File: SpringUtils.java From onetwo with Apache License 2.0 | 5 votes |
public static PropertiesFactoryBean createPropertiesBySptring(JFishProperties properties, String...classpaths) { // PropertiesFactoryBean pfb = new PropertiesFactoryBean(); PropertiesFactoryBean pfb = new JFishPropertiesFactoryBean(properties); pfb.setIgnoreResourceNotFound(true); org.springframework.core.io.Resource[] resources = new org.springframework.core.io.Resource[classpaths.length]; int index = 0; for(String classpath : classpaths){ resources[index++] = classpath(classpath); } pfb.setLocations(resources); return pfb; }
Example #23
Source File: TppAccountsControllerTest.java From XS2A-Sandbox with Apache License 2.0 | 5 votes |
@Test void downloadAccountTemplate() { // Given when(downloadResourceService.getResourceByTemplate(any())).thenReturn(null); // When ResponseEntity<Resource> response = accountsController.downloadAccountTemplate(); // Then assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); }
Example #24
Source File: ConfigurablePropertiesModule.java From attic-rave with Apache License 2.0 | 5 votes |
/** * Returns a Resource that contains property key-value pairs. * If no system property is set for the resource location, the default location is used * * @return the {@link Resource} with the */ private Resource getPropertyResource() { final String overrideProperty = System.getProperty(SHINDIG_OVERRIDE_PROPERTIES); if (StringUtils.isBlank(overrideProperty)) { return new ClassPathResource(DEFAULT_PROPERTIES); } else if (overrideProperty.startsWith(CLASSPATH)) { return new ClassPathResource(overrideProperty.trim().substring(CLASSPATH.length())); } else { return new FileSystemResource(overrideProperty.trim()); } }
Example #25
Source File: EncodedResource.java From spring4-understanding with Apache License 2.0 | 5 votes |
private EncodedResource(Resource resource, String encoding, Charset charset) { super(); Assert.notNull(resource, "Resource must not be null"); this.resource = resource; this.encoding = encoding; this.charset = charset; }
Example #26
Source File: PathResourceResolverTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void resolveFromClasspath() throws IOException { Resource location = new ClassPathResource("test/", PathResourceResolver.class); String path = "bar.css"; List<Resource> locations = singletonList(location); Resource actual = this.resolver.resolveResource(null, path, locations, null).block(TIMEOUT); assertEquals(location.createRelative(path), actual); }
Example #27
Source File: ResourceTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
private void doTestResource(Resource resource) throws IOException { assertEquals("Resource.class", resource.getFilename()); assertTrue(resource.getURL().getFile().endsWith("Resource.class")); Resource relative1 = resource.createRelative("ClassPathResource.class"); assertEquals("ClassPathResource.class", relative1.getFilename()); assertTrue(relative1.getURL().getFile().endsWith("ClassPathResource.class")); assertTrue(relative1.exists()); Resource relative2 = resource.createRelative("support/ResourcePatternResolver.class"); assertEquals("ResourcePatternResolver.class", relative2.getFilename()); assertTrue(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class")); assertTrue(relative2.exists()); }
Example #28
Source File: ManifestUtilsTest.java From spring-cloud-skipper with Apache License 2.0 | 5 votes |
@Test public void testCreateManifest() throws IOException { Resource resource = new ClassPathResource("/repositories/sources/test/ticktock/ticktock-1.0.1"); PackageReader packageReader = new DefaultPackageReader(); Package pkg = packageReader.read(resource.getFile()); assertThat(pkg).isNotNull(); Date date = new Date(666); Map<String, Object> log = new HashMap<>(); log.put("version", "666"); log.put("adate", new Date(666)); log.put("bool", true); log.put("array", "[a, b, c]"); Map<String, String> time = new HashMap<>(); time.put("version", "666"); Map<String, Object> map = new HashMap<>(); map.put("log", log); map.put("time", time); String manifest = ManifestUtils.createManifest(pkg, map); String dateAsStringWithQuotes = "\"" + date.toString() + "\""; assertThat(manifest).contains("\"version\": \"666\"").describedAs("Handle Integer"); assertThat(manifest).contains("\"bool\": \"true\"").describedAs("Handle Boolean"); assertThat(manifest).contains("\"adate\": " + dateAsStringWithQuotes).describedAs("Handle Date"); assertThat(manifest).contains("\"array\":\n - \"a\"\n - \"b\"\n - \"c\"").describedAs("Handle Array"); assertThat(manifest).contains("\"deploymentProperties\": !!null \"null\"").describedAs("Handle Null"); }
Example #29
Source File: DataBufferUtilsTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void readByteArrayResourcePositionAndTakeUntil() throws Exception { Resource resource = new ByteArrayResource("foobarbazqux" .getBytes()); Flux<DataBuffer> flux = DataBufferUtils.read(resource, 3, this.bufferFactory, 3); flux = DataBufferUtils.takeUntilByteCount(flux, 5); StepVerifier.create(flux) .consumeNextWith(stringConsumer("bar")) .consumeNextWith(stringConsumer("ba")) .expectComplete() .verify(Duration.ofSeconds(5)); }
Example #30
Source File: ResourceTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testServletContextResourceWithRelativePath() throws IOException { MockServletContext sc = new MockServletContext(); Resource resource = new ServletContextResource(sc, "dir/"); Resource relative = resource.createRelative("subdir"); assertEquals(new ServletContextResource(sc, "dir/subdir"), relative); }