org.springframework.core.io.ClassPathResource Java Examples
The following examples show how to use
org.springframework.core.io.ClassPathResource.
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: TestDataParserTest.java From justtestlah with Apache License 2.0 | 6 votes |
@Test public void testMultipleEntitiesInTestDatafile() throws IOException { TestDataObjectRegistry testDataObjectRegistry = new TestDataObjectRegistry(); target.setYamlParser(new Yaml()); target.setTestDataObjectRegistry(testDataObjectRegistry); assertThat( assertThrows( TestDataException.class, () -> target.parse( new ClassPathResource("MultipleEntities.yaml", this.getClass())), "Expected exception") .getMessage()) .as("check exception message") .isEqualTo( "The YAML test data file must contain exactly one root node, found 2: [Entity1, Entity2]"); }
Example #2
Source File: AbstractTestEntityEndpointRequest.java From spring-ws-security-soap-example with MIT License | 6 votes |
/** * Tests that the endpoint can handle invalid SOAP messages. */ @Test public final void testEndpoint_Invalid() throws Exception { final MockWebServiceClient mockClient; // Mocked client final RequestCreator requestCreator; // Creator for the request final ResponseMatcher responseMatcher; // Matcher for the response // Creates the request requestCreator = RequestCreators.withSoapEnvelope( new ClassPathResource(requestEnvelopeInvalidPath)); // Creates the response matcher responseMatcher = ResponseMatchers.clientOrSenderFault(); // Creates the client mock mockClient = MockWebServiceClient.createClient(applicationContext); // Calls the endpoint mockClient.sendRequest(requestCreator).andExpect(responseMatcher); }
Example #3
Source File: Jaxb2MarshallerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void marshalAttachments() throws Exception { marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(BinaryObject.class); marshaller.setMtomEnabled(true); marshaller.afterPropertiesSet(); MimeContainer mimeContainer = mock(MimeContainer.class); Resource logo = new ClassPathResource("spring-ws.png", getClass()); DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile())); given(mimeContainer.convertToXopPackage()).willReturn(true); byte[] bytes = FileCopyUtils.copyToByteArray(logo.getInputStream()); BinaryObject object = new BinaryObject(bytes, dataHandler); StringWriter writer = new StringWriter(); marshaller.marshal(object, new StreamResult(writer), mimeContainer); assertTrue("No XML written", writer.toString().length() > 0); verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class)); }
Example #4
Source File: TrackerEventBundleServiceTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testCreateSingleEventData() throws IOException { TrackerBundle trackerBundle = renderService .fromJson( new ClassPathResource( "tracker/event_events_and_enrollment.json" ).getInputStream(), TrackerBundleParams.class ) .toTrackerBundle(); assertEquals( 8, trackerBundle.getEvents().size() ); List<TrackerBundle> trackerBundles = trackerBundleService.create( TrackerBundleParams.builder() .events( trackerBundle.getEvents() ).enrollments( trackerBundle.getEnrollments() ) .trackedEntities( trackerBundle.getTrackedEntities() ).build() ); assertEquals( 1, trackerBundles.size() ); trackerBundleService.commit( trackerBundles.get( 0 ) ); List<ProgramStageInstance> programStageInstances = programStageInstanceStore.getAll(); assertEquals( 8, programStageInstances.size() ); }
Example #5
Source File: StreamsTest.java From riptide with MIT License | 6 votes |
@Test void shouldCallConsumerWithJsonList() { server.expect(requestTo(url)).andRespond( withSuccess() .body(new ClassPathResource("account-list.json")) .contentType(APPLICATION_X_JSON_STREAM)); @SuppressWarnings("unchecked") final ThrowingConsumer<AccountBody, Exception> verifier = mock( ThrowingConsumer.class); unit.get("/accounts") .dispatch(status(), on(OK).call(streamOf(AccountBody.class), forEach(verifier)), anyStatus().call(this::fail)) .join(); verify(verifier).accept(new AccountBody("1234567890", "Acme Corporation")); verify(verifier).accept(new AccountBody("1234567891", "Acme Company")); verify(verifier).accept(new AccountBody("1234567892", "Acme GmbH")); verify(verifier).accept(new AccountBody("1234567893", "Acme SE")); verifyNoMoreInteractions(verifier); }
Example #6
Source File: ImpalaQueryEngine.java From entrada with GNU General Public License v3.0 | 6 votes |
@Override public boolean postCompact(TablePartition p) { log.info("Perform post-compaction actions"); log .info("Perform post-compaction actions, refresh and compute stats for table: {}", p.getTable()); Map<String, Object> values = templateValues(p.getTable(), p.getYear(), p.getMonth(), p.getDay(), p.getServer()); // update meta data to let impala know the files have been updated and recalculate partition // statistics String sqlComputeStats = TemplateUtil .template( new ClassPathResource("/sql/impala/compute-stats-" + p.getTable() + ".sql", getClass()), values); return refresh(p.getTable(), values) && execute(sqlComputeStats); }
Example #7
Source File: TrackedEntityProgramAttributeReservedValueTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override protected void setUpTest() throws IOException { renderService = _renderService; userService = _userService; Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService.fromMetadata( new ClassPathResource( "tracker/te_program_with_tea_reserved_values_metadata.json" ).getInputStream(), RenderFormat.JSON ); ObjectBundleParams params = new ObjectBundleParams(); params.setObjectBundleMode( ObjectBundleMode.COMMIT ); params.setImportStrategy( ImportStrategy.CREATE ); params.setObjects( metadata ); ObjectBundle bundle = objectBundleService.create( params ); ObjectBundleValidationReport validationReport = objectBundleValidationService.validate( bundle ); assertTrue( validationReport.getErrorReports().isEmpty() ); objectBundleService.commit( bundle ); }
Example #8
Source File: TestEntityEndpointUnsecure.java From spring-ws-security-soap-example with MIT License | 6 votes |
/** * Tests that the endpoint can handle SOAP requests with a valid payload. */ @Test public final void testEndpoint_Payload_Invalid() throws Exception { final MockWebServiceClient mockClient; // Mocked client final RequestCreator requestCreator; // Creator for the request final ResponseMatcher responseMatcher; // Matcher for the response // Creates the request requestCreator = RequestCreators .withPayload(new ClassPathResource(requestPayloadInvalidPath)); // Creates the response matcher responseMatcher = ResponseMatchers.clientOrSenderFault(); // Creates the client mock mockClient = MockWebServiceClient.createClient(applicationContext); // Calls the endpoint mockClient.sendRequest(requestCreator).andExpect(responseMatcher); }
Example #9
Source File: WebRequestDataBinderIntegrationTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void partListBinding() { PartListBean bean = new PartListBean(); partListServlet.setBean(bean); MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts.add("partList", "first value"); parts.add("partList", "second value"); Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); parts.add("partList", logo); template.postForLocation(baseUrl + "/partlist", parts); assertNotNull(bean.getPartList()); assertEquals(parts.get("partList").size(), bean.getPartList().size()); }
Example #10
Source File: PropertyBasedSshSessionFactoryTest.java From spring-cloud-config with Apache License 2.0 | 6 votes |
public static String getResourceAsString(String path) { try { Resource resource = new ClassPathResource(path); try (BufferedReader br = new BufferedReader( new InputStreamReader(resource.getInputStream()))) { StringBuilder builder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { builder.append(line).append('\n'); } return builder.toString(); } } catch (IOException e) { throw new IllegalStateException(e); } }
Example #11
Source File: AnyDispatchTest.java From riptide with MIT License | 6 votes |
@Test void shouldDispatchAny() throws IOException { server.expect(requestTo(url)).andRespond( withSuccess() .body(new ClassPathResource("account.json")) .contentType(APPLICATION_JSON)); final ClientHttpResponse response = unit.get(url) .dispatch(status(), on(CREATED).call(pass()), anyStatus().call(pass())) .join(); assertThat(response.getStatusCode(), is(OK)); assertThat(response.getHeaders().getContentType(), is(APPLICATION_JSON)); }
Example #12
Source File: ClusterCalculatorsTest.java From scava with Eclipse Public License 2.0 | 6 votes |
@Before public void testCreateAndStoreDistanceMatrix() { artifactRepository.deleteAll(); githubUserRepository.deleteAll(); relationRepository.deleteAll(); clusterRepository.deleteAll(); clusterizationRepository.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(); similarityManager.createAndStoreDistanceMatrix(simDependencyCalculator); assertEquals(((artifacts.size() * (artifacts.size() -1))/2), relationRepository.findAllByTypeName(simDependencyCalculator.getSimilarityName()).size()); } catch (IOException e) { logger.error(e.getMessage()); } }
Example #13
Source File: MultipartHttpMessageWriterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test // SPR-16402 public void singleSubscriberWithResource() throws IOException { UnicastProcessor<Resource> processor = UnicastProcessor.create(); Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); Mono.just(logo).subscribe(processor); MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder(); bodyBuilder.asyncPart("logo", processor, Resource.class); Mono<MultiValueMap<String, HttpEntity<?>>> result = Mono.just(bodyBuilder.build()); Map<String, Object> hints = Collections.emptyMap(); this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block(); MultiValueMap<String, Part> requestParts = parse(hints); assertEquals(1, requestParts.size()); Part part = requestParts.getFirst("logo"); assertEquals("logo", part.name()); assertTrue(part instanceof FilePart); assertEquals("logo.jpg", ((FilePart) part).filename()); assertEquals(MediaType.IMAGE_JPEG, part.headers().getContentType()); assertEquals(logo.getFile().length(), part.headers().getContentLength()); }
Example #14
Source File: EmbeddedSftpServer.java From java-examples with MIT License | 6 votes |
private PublicKey decodePublicKey() throws Exception { InputStream stream = new ClassPathResource("/keys/sftp_rsa.pub").getInputStream(); byte[] decodeBuffer = Base64.decodeBase64(StreamUtils.copyToByteArray(stream)); ByteBuffer bb = ByteBuffer.wrap(decodeBuffer); int len = bb.getInt(); byte[] type = new byte[len]; bb.get(type); if ("ssh-rsa".equals(new String(type))) { BigInteger e = decodeBigInt(bb); BigInteger m = decodeBigInt(bb); RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e); return KeyFactory.getInstance("RSA").generatePublic(spec); } else { throw new IllegalArgumentException("Only supports RSA"); } }
Example #15
Source File: DataValueSetServiceTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testImportDataValuesInvalidAttributeOptionComboOrgUnit() throws Exception { categoryOptionA.setOrganisationUnits( Sets.newHashSet( ouA, ouB ) ); categoryService.updateCategoryOption( categoryOptionA ); in = new ClassPathResource( "datavalueset/dataValueSetH.xml" ).getInputStream(); ImportSummary summary = dataValueSetService.saveDataValueSet( in ); assertEquals( summary.getConflicts().toString(), 1, summary.getConflicts().size() ); assertEquals( 2, summary.getImportCount().getImported() ); assertEquals( 0, summary.getImportCount().getUpdated() ); assertEquals( 0, summary.getImportCount().getDeleted() ); assertEquals( 1, summary.getImportCount().getIgnored() ); assertEquals( ImportStatus.WARNING, summary.getStatus() ); Collection<DataValue> dataValues = mockDataValueBatchHandler.getInserts(); assertNotNull( dataValues ); assertEquals( 2, dataValues.size() ); assertTrue( dataValues.contains( new DataValue( deA, peA, ouA, ocDef, ocA ) ) ); assertTrue( dataValues.contains( new DataValue( deB, peB, ouB, ocDef, ocA ) ) ); }
Example #16
Source File: LocalSessionFactoryBeanTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testLocalSessionFactoryBeanWithTypeDefinitions() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(new ClassPathResource("typeDefinitions.xml", getClass())); TypeTestLocalSessionFactoryBean sf = (TypeTestLocalSessionFactoryBean) xbf.getBean("&sessionFactory"); // Requires re-compilation when switching to Hibernate 3.5/3.6 // since Mappings changed from a class to an interface TypeDef type1 = sf.mappings.getTypeDef("type1"); TypeDef type2 = sf.mappings.getTypeDef("type2"); assertEquals("mypackage.MyTypeClass", type1.getTypeClass()); assertEquals(2, type1.getParameters().size()); assertEquals("value1", type1.getParameters().getProperty("param1")); assertEquals("othervalue", type1.getParameters().getProperty("otherParam")); assertEquals("mypackage.MyOtherTypeClass", type2.getTypeClass()); assertEquals(1, type2.getParameters().size()); assertEquals("myvalue", type2.getParameters().getProperty("myParam")); }
Example #17
Source File: ObjectBundleServiceTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test @Ignore //TODO fix public void testCreateAndUpdateMetadata3() throws IOException { Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService.fromMetadata( new ClassPathResource( "dxf2/de_create_and_update3.json" ).getInputStream(), RenderFormat.JSON ); ObjectBundleParams params = new ObjectBundleParams(); params.setObjectBundleMode( ObjectBundleMode.COMMIT ); params.setImportStrategy( ImportStrategy.CREATE_AND_UPDATE ); params.setObjects( metadata ); ObjectBundle bundle = objectBundleService.create( params ); assertTrue( objectBundleValidationService.validate( bundle ).getErrorReports().isEmpty() ); objectBundleService.commit( bundle ); DataElement dataElementE = manager.get( DataElement.class, "deabcdefghE" ); assertNotNull( dataElementE ); assertEquals( "DEE", dataElementE.getName() ); assertEquals( "DECE", dataElementE.getCode() ); assertEquals( "DESE", dataElementE.getShortName() ); assertEquals( "DEDE", dataElementE.getDescription() ); }
Example #18
Source File: SQLErrorCodesFactoryTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testInvalidUserDefinedCodeFormat() { class TestSQLErrorCodesFactory extends SQLErrorCodesFactory { @Override protected Resource loadResource(String path) { if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) { // Guaranteed to be on the classpath, but most certainly NOT XML return new ClassPathResource("SQLExceptionTranslator.class", SQLErrorCodesFactoryTests.class); } return null; } } // Should have failed to load without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0); assertEquals(0, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length); }
Example #19
Source File: DataValueSetServiceTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testImportDataValuesXmlDryRun() throws Exception { in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream(); ImportOptions importOptions = new ImportOptions() .setDryRun( true ) .setIdScheme( "UID" ) .setDataElementIdScheme( "UID" ) .setOrgUnitIdScheme( "UID" ); ImportSummary summary = dataValueSetService.saveDataValueSet( in, importOptions ); assertEquals( ImportStatus.SUCCESS, summary.getStatus() ); assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() ); Collection<DataValue> dataValues = mockDataValueBatchHandler.getInserts(); assertNotNull( dataValues ); assertEquals( 0, dataValues.size() ); }
Example #20
Source File: StreamConverterTest.java From riptide with MIT License | 6 votes |
@Test void shouldSupportGenericReadStream() throws Exception { final Type type = Streams.streamOf(AccountBody.class).getType(); final StreamConverter<AccountBody> unit = new StreamConverter<>(new ObjectMapper().findAndRegisterModules(), singletonList(APPLICATION_X_JSON_STREAM)); final HttpInputMessage input = mockWithContentType(APPLICATION_X_JSON_STREAM); when(input.getBody()).thenReturn(new ClassPathResource("account-stream.json").getInputStream()); final Stream<AccountBody> stream = unit.read(type, null, input); @SuppressWarnings("unchecked") final Consumer<? super AccountBody> verifier = mock(Consumer.class); stream.forEach(verifier); verify(verifier).accept(new AccountBody("1234567890", "Acme Corporation")); verify(verifier).accept(new AccountBody("1234567891", "Acme Company")); verify(verifier).accept(new AccountBody("1234567892", "Acme GmbH")); verify(verifier).accept(new AccountBody("1234567893", "Acme SE")); verify(verifier, times(4)).accept(any(AccountBody.class)); }
Example #21
Source File: TrackerEventBundleServiceTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override protected void setUpTest() throws IOException { renderService = _renderService; userService = _userService; Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> metadata = renderService .fromMetadata( new ClassPathResource( "tracker/event_metadata.json" ).getInputStream(), RenderFormat.JSON ); ObjectBundleParams params = new ObjectBundleParams(); params.setObjectBundleMode( ObjectBundleMode.COMMIT ); params.setImportStrategy( ImportStrategy.CREATE ); params.setObjects( metadata ); ObjectBundle bundle = objectBundleService.create( params ); ObjectBundleValidationReport validationReport = objectBundleValidationService.validate( bundle ); assertTrue( validationReport.getErrorReports().isEmpty() ); objectBundleService.commit( bundle ); }
Example #22
Source File: EhCacheSupportTests.java From java-technology-stack with MIT License | 6 votes |
public void testCacheManagerFromConfigFile() { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass())); cacheManagerFb.setCacheManagerName("myCacheManager"); cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); assertTrue("Correct number of caches loaded", cm.getCacheNames().length == 1); Cache myCache1 = cm.getCache("myCache1"); assertFalse("myCache1 is not eternal", myCache1.getCacheConfiguration().isEternal()); assertTrue("myCache1.maxElements == 300", myCache1.getCacheConfiguration().getMaxEntriesLocalHeap() == 300); } finally { cacheManagerFb.destroy(); } }
Example #23
Source File: ResourceHttpRequestHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void initAllowedLocationsWithExplicitConfiguration() throws Exception { ClassPathResource location1 = new ClassPathResource("test/", getClass()); ClassPathResource location2 = new ClassPathResource("testalternatepath/", getClass()); PathResourceResolver pathResolver = new PathResourceResolver(); pathResolver.setAllowedLocations(location1); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setResourceResolvers(Collections.singletonList(pathResolver)); handler.setServletContext(new MockServletContext()); handler.setLocations(Arrays.asList(location1, location2)); handler.afterPropertiesSet(); Resource[] locations = pathResolver.getAllowedLocations(); assertEquals(1, locations.length); assertEquals("test/", ((ClassPathResource) locations[0]).getPath()); }
Example #24
Source File: WebJarsResourceResolverTests.java From spring-analysis-note with MIT License | 5 votes |
@Before public void setup() { // for this to work, an actual WebJar must be on the test classpath this.locations = Collections.singletonList(new ClassPathResource("/META-INF/resources/webjars")); this.resolver = new WebJarsResourceResolver(); this.chain = mock(ResourceResolverChain.class); }
Example #25
Source File: BeanNameGenerationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Before public void setUp() { this.beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); reader.loadBeanDefinitions(new ClassPathResource("beanNameGeneration.xml", getClass())); }
Example #26
Source File: PersonJobConfig.java From spring-batch-rest with Apache License 2.0 | 5 votes |
@Bean FlatFileItemReader<Person> personReader() { return new FlatFileItemReaderBuilder<Person>() .name("personItemReader") .resource(new ClassPathResource("person.csv")) .delimited() .names(new String[]{"firstName", "lastName"}) .fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{ setTargetType(Person.class); }}) .build(); }
Example #27
Source File: TrackedEntityProgramAttributeEncryptionTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testTrackedEntityProgramAttributeEncryptedValue() throws IOException { TrackerBundle trackerBundle = renderService.fromJson( new ClassPathResource( "tracker/te_program_with_tea_encryption_data.json" ).getInputStream(), TrackerBundleParams.class ).toTrackerBundle(); List<TrackerBundle> trackerBundles = trackerBundleService.create( TrackerBundleParams.builder() .trackedEntities( trackerBundle.getTrackedEntities() ) .enrollments( trackerBundle.getEnrollments() ) .events( trackerBundle.getEvents() ) .build() ); assertEquals( 1, trackerBundles.size() ); trackerBundleService.commit( trackerBundles.get( 0 ) ); List<TrackedEntityInstance> trackedEntityInstances = manager.getAll( TrackedEntityInstance.class ); assertEquals( 1, trackedEntityInstances.size() ); TrackedEntityInstance trackedEntityInstance = trackedEntityInstances.get( 0 ); List<TrackedEntityAttributeValue> attributeValues = trackedEntityAttributeValueService.getTrackedEntityAttributeValues( trackedEntityInstance ); assertEquals( 5, attributeValues.size() ); // not really a great test, but we are using a random seed for salt, so it changes on every run... we might want to // add another EncryptionConfig test profile RowCallbackHandler handler = resultSet -> assertNotNull( resultSet.getString( "encryptedvalue" ) ); jdbcTemplate.query( "select * from trackedentityattributevalue where encryptedvalue is not null ", handler ); }
Example #28
Source File: ConfigurableMimeFileTypeMapTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void withCustomMappingLocation() throws Exception { Resource resource = new ClassPathResource("test.mime.types", getClass()); ConfigurableMimeFileTypeMap ftm = new ConfigurableMimeFileTypeMap(); ftm.setMappingLocation(resource); ftm.afterPropertiesSet(); assertEquals("Invalid content type for foo", "text/foo", ftm.getContentType("foobar.foo")); assertEquals("Invalid content type for bar", "text/bar", ftm.getContentType("foobar.bar")); assertEquals("Invalid content type for fimg", "image/foo", ftm.getContentType("foobar.fimg")); assertEquals("Invalid content type for bimg", "image/bar", ftm.getContentType("foobar.bimg")); }
Example #29
Source File: PathResourceResolverTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void checkServletContextResource() throws Exception { Resource classpathLocation = new ClassPathResource("test/", PathResourceResolver.class); MockServletContext context = new MockServletContext(); ServletContextResource servletContextLocation = new ServletContextResource(context, "/webjars/"); ServletContextResource resource = new ServletContextResource(context, "/webjars/webjar-foo/1.0/foo.js"); assertFalse(this.resolver.checkResource(resource, classpathLocation)); assertTrue(this.resolver.checkResource(resource, servletContextLocation)); }
Example #30
Source File: PathResourceResolver.java From spring-analysis-note with MIT License | 5 votes |
private boolean isResourceUnderLocation(Resource resource, Resource location) throws IOException { if (resource.getClass() != location.getClass()) { return false; } String resourcePath; String locationPath; if (resource instanceof UrlResource) { resourcePath = resource.getURL().toExternalForm(); locationPath = StringUtils.cleanPath(location.getURL().toString()); } else if (resource instanceof ClassPathResource) { resourcePath = ((ClassPathResource) resource).getPath(); locationPath = StringUtils.cleanPath(((ClassPathResource) location).getPath()); } else if (resource instanceof ServletContextResource) { resourcePath = ((ServletContextResource) resource).getPath(); locationPath = StringUtils.cleanPath(((ServletContextResource) location).getPath()); } else { resourcePath = resource.getURL().getPath(); locationPath = StringUtils.cleanPath(location.getURL().getPath()); } if (locationPath.equals(resourcePath)) { return true; } locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/"); return (resourcePath.startsWith(locationPath) && !isInvalidEncodedPath(resourcePath)); }