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

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

Introduction

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

Prototype

@Override
public InputStream getInputStream() throws IOException 

Source Link

Document

This implementation opens an InputStream for the given class path resource.

Usage

From source file:example.springdata.rest.stores.StoreInitializer.java

/**
 * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to
 * persisted.//from  w w w.ja v a2  s .  c  om
 * 
 * @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.setFieldSetMapper(fields -> {

        Point location = new Point(fields.readDouble("Longitude"), fields.readDouble("Latitude"));
        Address address = new Address(fields.readString("Street Address"), fields.readString("City"),
                fields.readString("Zip"), location);

        return new Store(fields.readString("Name"), address);
    });

    lineMapper.setLineTokenizer(tokenizer);
    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:example.store.StoreInitializer.java

/**
 * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to
 * persisted.//from   w w w . java 2  s  .co  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:com.fccfc.framework.common.utils.PropertyHolder.java

/**
 * ?APDPlatLoggerImpl ??LOG.setLocale(getLogLanguage())
 * ???//from  w w  w .  j av  a 2s  .co  m
 */
private static void init() {
    String systemConfig = "/config.properties";
    ClassPathResource cr = null;
    try {
        cr = new ClassPathResource(systemConfig);
        load(cr.getInputStream(), PROPERTIES);
        log.info("?:" + systemConfig);
    } catch (Exception e) {
        log.info("?" + systemConfig + "!", e);
    }

    String extendPropertyFiles = PROPERTIES.get("extend.property.files");
    if (extendPropertyFiles != null && !"".equals(extendPropertyFiles.trim())) {
        String[] files = extendPropertyFiles.trim().split(",");
        for (String file : files) {
            try {
                cr = new ClassPathResource(file);
                load(cr.getInputStream(), PROPERTIES);
                log.info("?" + file);
            } catch (Exception e) {
                log.info("?" + file + "?", e);
            }
        }
    }
    log.info("?");
    log.info("*********************************************");
    PROPERTIES.keySet().forEach(propertyName -> {
        log.info("  " + propertyName + " = " + PROPERTIES.get(propertyName));
    });
    log.info("***********************************************************");
}

From source file:com.ankang.report.config.ReportConfig.java

public static void loadReportConfig(String classPath) {

    if ((null == classPath || REPORT.equals(classPath)) && !isLoad) {

        classPath = REPORT;/* w w  w .ja v a2s.  c o  m*/
        isLoad = Boolean.TRUE;
    }
    logger.info("load properties " + classPath);

    ClassPathResource cp = new ClassPathResource(classPath);

    try {
        if (cp.exists()) {
            ps.load(cp.getInputStream());
            convertMap((Map) ps);
            ps.clear();
        }
    } catch (IOException e) {
        throw new ReportException("File read exception file.[%s]", classPath);
    }

}

From source file:org.cloudfoundry.caldecott.client.TunnelHelper.java

private static File copyCaldecottZipFile(ClassPathResource cpr) throws IOException {
    File temp = File.createTempFile("caldecott", "zip");
    InputStream in = cpr.getInputStream();
    OutputStream out = new FileOutputStream(temp);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = in.read(bytes)) != -1) {
        out.write(bytes, 0, read);//  w  w  w . j a  v  a  2  s  . co m
    }
    in.close();
    out.flush();
    out.close();
    return temp;
}

From source file:com.loy.MicroServiceConsole.java

@SuppressWarnings("rawtypes")
static void init() {

    ClassPathResource classPathResource = new ClassPathResource("application.yml");
    Yaml yaml = new Yaml();
    Map result = null;//from   w w  w .  j a v  a  2 s.  c  o  m
    try {
        result = (Map) yaml.load(classPathResource.getInputStream());
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String platformStr = result.get("platform").toString();
    String version = result.get("version").toString();
    String jvmOption = result.get("jvmOption").toString();
    @SuppressWarnings("unchecked")
    List<String> projects = (List<String>) result.get("projects");
    platform = Platform.valueOf(platformStr);

    final Runtime runtime = Runtime.getRuntime();
    File pidsForder = new File("./pids");
    if (!pidsForder.exists()) {
        pidsForder.mkdir();
    } else {
        File[] files = pidsForder.listFiles();
        if (files != null) {
            for (File f : files) {
                f.deleteOnExit();
                String pidStr = f.getName();
                try {
                    Long pid = new Long(pidStr);
                    if (Processes.isProcessRunning(platform, pid)) {
                        if (Platform.Windows == platform) {
                            Processes.tryKillProcess(null, platform, new NullProcessor(), pid);
                        } else {
                            Processes.killProcess(null, platform, new NullProcessor(), pid);
                        }

                    }
                } catch (Exception ex) {
                }
            }
        }
    }

    File currentForder = new File("");
    String root = currentForder.getAbsolutePath();
    root = root.replace(File.separator + "build" + File.separator + "libs", "");
    root = root.replace(File.separator + "e-example-ms-start", "");
    final String rootPath = root;
    new Thread(new Runnable() {
        @Override
        public void run() {
            int size = projects.size();
            int index = 1;
            for (String value : projects) {
                String path = value;
                String[] values = value.split("/");
                value = values[values.length - 1];
                value = rootPath + "/" + path + "/build/libs/" + value + "-" + version + ".jar";
                final String command = value;
                try {
                    Process process = runtime
                            .exec("java " + jvmOption + " -Dfile.encoding=UTF-8 -jar " + command);
                    Long pid = Processes.processId(process);
                    pids.add(pid);
                    File pidsFile = new File("./pids", pid.toString());
                    pidsFile.createNewFile();
                    new WriteLogThread(process.getInputStream()).start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                synchronized (lock) {
                    try {
                        if (index < size) {
                            lock.wait();
                        } else {
                            index++;
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:org.paxml.testng.PaxmlListener.java

private static void copyFile(String name, File destDir) throws IOException {

    ClassPathResource res = new ClassPathResource(REPORTER_DIR + "/" + name);
    FileOutputStream out = null;/* w w w .  j  av a  2s. c  o  m*/
    InputStream in = null;
    try {
        out = new FileOutputStream(new File(destDir, name));
        in = res.getInputStream();
        IOUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.KratuMain.java

/**
 * Prints the sample properties file on the default output.
 *//* w  w w.  java2 s.co m*/
private static void printSamplePropertiesFile() {

    System.out.println("\n  File: kratubackend-sample.properties example");

    ClassPathResource sampleFile = new ClassPathResource(CLASSPATH_AW_REPORT_MODEL_PROPERTIES_LOCATION);
    Scanner fileScanner = null;
    try {
        fileScanner = new Scanner(sampleFile.getInputStream());
        while (fileScanner.hasNext()) {
            System.out.println(fileScanner.nextLine());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileScanner != null) {
            fileScanner.close();
        }
    }
}

From source file:com.google.api.ads.adwords.awreporting.server.AwReportingServer.java

/**
 * Prints the sample properties file on the default output.
 *//*from  w ww  .ja  v  a  2s .c o  m*/
private static void printSamplePropertiesFile() {

    System.out.println("\n  File: aw-reporting-server-sample.properties example");

    ClassPathResource sampleFile = new ClassPathResource(DAFAULT_PROPERTIES_LOCATION);
    Scanner fileScanner = null;
    try {
        fileScanner = new Scanner(sampleFile.getInputStream());
        while (fileScanner.hasNext()) {
            System.out.println(fileScanner.nextLine());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileScanner != null) {
            fileScanner.close();
        }
    }
}

From source file:com.github.totyumengr.minicubes.core.MiniCubeTest.java

@BeforeClass
public static void prepare() throws Throwable {

    Assert.assertTrue(new DoubleDouble(1926).doubleValue() == 1926.0);
    Assert.assertTrue(new DoubleDouble("1926").doubleValue() == 0.1926);
    Assert.assertTrue(new DoubleDouble("1926.000").doubleValue() == 1926.0);

    String dataFile = System.getProperty("dataFile", "data_fc_bd_qs_day_detail_20140606.data");

    FactTableBuilder builder = new FactTableBuilder().build("MiniCubeTest")
            .addDimColumns(Arrays.asList(new String[] { "the_date", "tradeId", "productLineId", "postId" }))
            .addIndColumns(Arrays.asList(new String[] { "csm", "cash", "click", "shw" }));

    long startTime = System.currentTimeMillis();
    LOGGER.info("prepare {} - start: {}", dataFile, startTime);
    ClassPathResource resource = new ClassPathResource(dataFile);
    BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
    String line = null;/*from   ww w .  jav  a2 s .c  o m*/
    Integer index = 0;
    while ((line = reader.readLine()) != null) {
        String[] split = line.split("\t");
        index++;
        if (index % 100000 == 0) {
            LOGGER.debug("Load {} records", index);
        }
        builder.addDimDatas(index, Arrays.asList(new Integer[] { Integer.valueOf(split[0]),
                Integer.valueOf(split[1]), Integer.valueOf(split[2]), Integer.valueOf(split[3]) }));
        builder.addIndDatas(index,
                Arrays.asList(new DoubleDouble[] { new DoubleDouble(split[4]), new DoubleDouble(split[5]),
                        new DoubleDouble(split[6] + ".00000000"), new DoubleDouble(split[7] + ".00000000") }));
    }
    reader.close();
    LOGGER.info("prepare - end: {}, {}ms", System.currentTimeMillis(), System.currentTimeMillis() - startTime);

    miniCube = new MiniCube(builder.done());
}