类org.springframework.core.io.ClassPathResource源码实例Demo

下面列出了怎么用org.springframework.core.io.ClassPathResource的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: dhis2-core   文件: ObjectBundleServiceTest.java
@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() );
}
 
@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"));
}
 
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);
	}
}
 
@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());
}
 
源代码5 项目: riptide   文件: StreamsTest.java
@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);
}
 
源代码6 项目: riptide   文件: StreamConverterTest.java
@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));
}
 
@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));
}
 
@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() );
}
 
@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 );
}
 
源代码10 项目: dhis2-core   文件: DataValueSetServiceTest.java
@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() );
}
 
源代码11 项目: java-examples   文件: EmbeddedSftpServer.java
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");
    }
}
 
源代码12 项目: justtestlah   文件: TestDataParserTest.java
@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]");
}
 
/**
 * 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);
}
 
源代码14 项目: scava   文件: ClusterCalculatorsTest.java
@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());
	}
}
 
/**
 * 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);
}
 
源代码16 项目: entrada   文件: ImpalaQueryEngine.java
@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);
}
 
源代码17 项目: riptide   文件: AnyDispatchTest.java
@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));
}
 
@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());
}
 
源代码19 项目: dhis2-core   文件: DataValueSetServiceTest.java
@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 ) ) );
}
 
@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);
}
 
源代码21 项目: dhis2-core   文件: TrackerEventBundleServiceTest.java
@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 );
}
 
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();
	}
}
 
@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());
}
 
源代码24 项目: spring-batch-rest   文件: PersonJobConfig.java
@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();
}
 
源代码25 项目: cloudbreak   文件: FreeipaJinjaTester.java
private Collection<File> collectAllSlsFiles(String salt) throws IOException {
    File file = new ClassPathResource(salt).getFile();
    return FileUtils.listFiles(
            file,
            new RegexFileFilter("^(.*.sls)"),
            DirectoryFileFilter.DIRECTORY
    );
}
 
源代码26 项目: entrada   文件: TemplateUtil.java
private static String readTemplate(ClassPathResource template) {
  try (InputStream is = template.getInputStream()) {
    return IOUtils.toString(template.getInputStream(), StandardCharsets.UTF_8.name());
  } catch (IOException e) {
    throw new ApplicationException("Could not load file " + template, e);
  }
}
 
源代码27 项目: alfresco-repository   文件: ImapMessageTest.java
private void importInternal(String acpName, NodeRef space) throws IOException
{
    // Importing IMAP test acp
    ClassPathResource acpResource = new ClassPathResource(acpName);
    ACPImportPackageHandler acpHandler = new ACPImportPackageHandler(acpResource.getFile(), null);
    Location importLocation = new Location(space);
    importerService.importView(acpHandler, importLocation, null, null);
}
 
@Test
public void testResourceArrayPropertyEditor() throws IOException {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD);
	Service service = (Service) ctx.getBean("service");
	assertEquals(3, service.getResources().length);
	List<Resource> resources = Arrays.asList(service.getResources());
	assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_A).getFile())));
	assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_B).getFile())));
	assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_C).getFile())));
	ctx.close();
}
 
@PostConstruct
@SuppressWarnings("unchecked")
public void init() throws Exception {
    Resource resource = new ClassPathResource("users.json");
    ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();
    List<User> userList = mapper.readValue(resource.getInputStream(), new TypeReference<List<User>>() { });
    Map<String,User> userMap = new TreeMap<>();

    for (User user : userList)
        userMap.put(user.getEmail(), user);

    this.users = Collections.unmodifiableMap(userMap);
}
 
源代码30 项目: spring-batch   文件: CapitalizeNamesJobConfig.java
@Bean
public FlatFileItemReader<Person> itemReader() {
  return new FlatFileItemReaderBuilder<Person>()
      .name("personItemReader")
      .resource(new ClassPathResource("csv/persons.csv"))
      .delimited().names(new String[] {"firstName", "lastName"})
      .targetType(Person.class).build();
}
 
 同包方法