Example usage for org.springframework.core.io ClassPathResource ClassPathResource

List of usage examples for org.springframework.core.io ClassPathResource ClassPathResource

Introduction

In this page you can find the example usage for org.springframework.core.io ClassPathResource ClassPathResource.

Prototype

public ClassPathResource(String path) 

Source Link

Document

Create a new ClassPathResource for ClassLoader usage.

Usage

From source file:example.store.StoreInitializer.java

/**
 * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to
 * persisted./*  w  ww . j  a  v a2 s . c  o  m*/
 *
 * @return
 * @throws Exception
 */
public static List<Store> readStores() throws Exception {

    ClassPathResource resource = new ClassPathResource("starbucks.csv");
    Scanner scanner = new Scanner(resource.getInputStream());
    String line = scanner.nextLine();
    scanner.close();

    FlatFileItemReader<Store> itemReader = new FlatFileItemReader<Store>();
    itemReader.setResource(resource);

    // DelimitedLineTokenizer defaults to comma as its delimiter
    DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
    tokenizer.setNames(line.split(","));
    tokenizer.setStrict(false);

    DefaultLineMapper<Store> lineMapper = new DefaultLineMapper<Store>();
    lineMapper.setLineTokenizer(tokenizer);
    lineMapper.setFieldSetMapper(StoreFieldSetMapper.INSTANCE);
    itemReader.setLineMapper(lineMapper);
    itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
    itemReader.setLinesToSkip(1);
    itemReader.open(new ExecutionContext());

    List<Store> stores = new ArrayList<>();
    Store store = null;

    do {

        store = itemReader.read();

        if (store != null) {
            stores.add(store);
        }

    } while (store != null);

    return stores;
}

From source file:net.javacrumbs.springws.test.template.FreeMarkerTemplateProcessorTest.java

@Test
public void testTemplate() throws IOException {
    WsTestContextHolder.getTestContext().setAttribute("number", 2);
    WebServiceMessage request = createMessage("xml/valid-message2.xml");
    ClassPathResource template = new ClassPathResource("mock-responses/test/freemarker-response.xml");
    Resource resource = processor.processTemplate(template, request);

    Document controlDocument = getXmlUtil()
            .loadDocument(new ClassPathResource("xml/resolved-different-response.xml"));
    Document responseDocument = getXmlUtil().loadDocument(resource);
    Diff diff = new Diff(controlDocument, responseDocument);
    assertTrue(diff.toString(), diff.similar());

    WsTestContextHolder.getTestContext().clear();
}

From source file:net.javacrumbs.springws.test.validator.SchemaRequestValidatorTest.java

protected SchemaRequestValidator createValidator() throws Exception {
    SchemaRequestValidator validator = new SchemaRequestValidator();
    validator.setSchema(new ClassPathResource("xml/schema.xsd"));
    validator.setSchemaLanguage(XmlValidatorFactory.SCHEMA_W3C_XML);
    assertEquals(1, validator.getSchemas().length);
    validator.afterPropertiesSet();/*  w w  w .ja  va  2s.c o m*/
    assertEquals(XmlValidatorFactory.SCHEMA_W3C_XML, validator.getSchemaLanguage());
    return validator;
}

From source file:com.graphaware.test.data.GraphgenPopulatorTest.java

@Test
public void shouldPopulateDatabaseFromSingleFile() {
    new GraphgenPopulator() {
        @Override/*from   w  w  w . j  a  v a 2s. co  m*/
        protected String file() throws IOException {
            return new ClassPathResource("graphgen.cyp").getFile().getAbsolutePath();
        }
    }.populate(getDatabase());

    assertSameGraph(getDatabase(),
            "CREATE " + "(n1:Person {name: 'Isabell McGlynn'})," + "(n2:Person {name: 'Kelton Kuhn'}),"
                    + "(n3:Person {name: 'Chesley Feil'})," + "(n4:Person {name: 'Adrain Daugherty'}),"
                    + "(n5:Person {name: 'Kyleigh Stehr'})," + "(n1)-[:KNOWS]->(n5)," + "(n1)-[:KNOWS]->(n3),"
                    + "(n2)-[:KNOWS]->(n1)," + "(n3)-[:KNOWS]->(n5)," + "(n4)-[:KNOWS]->(n5),"
                    + "(n4)-[:KNOWS]->(n2)");
}

From source file:TopicsTest.java

@Test
public void testJDBCTemplaFindById() {

    ListableBeanFactory bf;/*w  w w.ja  va2 s  .  c o  m*/
    bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
    ITopicsMetier m = (ITopicsMetier) bf.getBean("topicsMetier");
    System.out.print("Je suis ici");
    List<Topics> to = m.findAllById(1);

    //System.out.print(to.getTopic_desc() + "" + to.getCat_id());
}

From source file:be.jacobsvanroy.springsqlunit.sql.SqlRunner.java

private void runSqlFile(String sqlFile, DataSource dataSource) {
    ClassPathResource resource = new ClassPathResource(sqlFile);
    File scriptFile = getFile(resource);
    runSqlFile(scriptFile, dataSource);//w w  w.  j a v a 2s. co  m
}

From source file:slina.mb.utils.LogFileReaderImpl.java

@Override
public List<String> readFile(String fileName) {

    List<String> lines = new ArrayList<String>();

    try {/*from w w  w. ja  v a  2 s .c  o  m*/

        long before = System.currentTimeMillis();

        File file = new File(fileName);

        if (!file.isFile()) {

            if (this.checkClassPath) {

                Resource classPathResource = new ClassPathResource(fileName);
                file = classPathResource.getFile();
            }

        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = reader.readLine();

        while (line != null) {
            lines.add(line);
            line = reader.readLine();
        }

        long after = System.currentTimeMillis();
        reader.close();
        LOGGER.info("conv. run took " + (after - before) + " ms, size = " + lines.size());
        return lines;

    } catch (IOException e) {
        LOGGER.error(e);
        return lines;
    }

}

From source file:org.springframework.cloud.config.monitor.CompositePropertyPathNotificationExtractorTests.java

@Test
public void githubSample() throws Exception {
    // See https://developer.github.com/v3/activity/events/types/#pushevent
    Map<String, Object> value = new ObjectMapper().readValue(
            new ClassPathResource("github.json").getInputStream(), new TypeReference<Map<String, Object>>() {
            });//from www  . ja  va2  s .c  o m
    this.headers.set("X-Github-Event", "push");
    PropertyPathNotification extracted = this.extractor.extract(this.headers, value);
    assertNotNull(extracted);
    assertEquals("README.md", extracted.getPaths()[0]);
}

From source file:fm.lastify.config.LastifyFmWebappConfig.java

/**
 * Used to configure the in-memory HSQLDB database Remove this method if
 * different datasource is used//from w  w  w  .  j  a va 2 s.c om
 * 
 * @throws IOException
 */
@PostConstruct
public void createDatabaseTable() throws IOException {
    Resource resource = new ClassPathResource(
            "org/springframework/social/connect/jdbc/JdbcUsersConnectionRepository.sql");
    BufferedInputStream is = new BufferedInputStream(resource.getInputStream());
    final char[] buffer = new char[0x10000];
    StringBuilder out = new StringBuilder();
    Reader in = new InputStreamReader(resource.getInputStream(), "UTF-8");
    int read;
    do {
        read = in.read(buffer, 0, buffer.length);
        if (read > 0) {
            out.append(buffer, 0, read);
        }
    } while (read >= 0);

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.execute(out.toString());

}

From source file:com.baidu.cc.spring.ConfigCenterPropertyExtractorTest.java

/**
 * test property extractor/* w  ww .  ja v  a 2 s  .c  o m*/
 * this test method is ignored due to local environment required.
 * 
 * @throws Exception throw out all exception to break unit test and mark failed.
 */
@Ignore
@Test
public void testPropertyExtractorNoMock() throws Exception {
    PropertyPlaceholderConfigurer extractor = new PropertyPlaceholderConfigurer();
    ClassPathResource cpr = new ClassPathResource("/com/baidu/cc/spring/test.properties");
    extractor.setLocation(cpr);

    ConfigCenterPropertyPlaceholderConfigurer importer;
    importer = new ConfigCenterPropertyPlaceholderConfigurer();

    importer.setCcUser("test1");
    importer.setCcPassword("123");
    importer.setCcVersion(586);
    importer.setCcServerUrl("http://localhost:8080/rpc/ExtConfigServerService");
    importer.setReadTimeout(5000);

    //initial importer
    ConfigCenterPropertyPlaceholderConfigurerTest test = new ConfigCenterPropertyPlaceholderConfigurerTest();
    importer.setApplicationContext(test.appContext);
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    importer.postProcessBeanFactory(beanFactory);

    ConfigCenterPropertyExtractor ccpe = new ConfigCenterPropertyExtractor();
    ccpe.setCcVersion(586);
    ccpe.setExtractor(extractor);
    ccpe.setImporter(importer);

    ccpe.afterPropertiesSet();
}