Example usage for java.nio.file Files write

List of usage examples for java.nio.file Files write

Introduction

In this page you can find the example usage for java.nio.file Files write.

Prototype

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
        throws IOException 

Source Link

Document

Write lines of text to a file.

Usage

From source file:de.fatalix.book.importer.BookMigrator.java

private static void exportBatchWise(SolrServer server, File exportFolder, int batchSize, int offset, Gson gson)
        throws SolrServerException, IOException {

    QueryResponse response = SolrHandler.searchSolrIndex(server, "*:*", batchSize, offset);
    List<BookEntry> bookEntries = response.getBeans(BookEntry.class);
    System.out.println(/*from  ww  w.j  a  va 2s .c  o m*/
            "Retrieved " + (bookEntries.size() + offset) + " of " + response.getResults().getNumFound());
    for (BookEntry bookEntry : bookEntries) {
        String bookTitle = bookEntry.getTitle();
        bookTitle = bookTitle.replaceAll(":", " ");
        File bookFolder = new File(exportFolder, bookEntry.getAuthor() + "-" + bookTitle);
        bookFolder.mkdirs();
        if (bookEntry.getCover() != null) {
            if (bookEntry.getEpub() != null) {
                File bookData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".epub");
                Files.write(bookData.toPath(), bookEntry.getMobi(), StandardOpenOption.CREATE_NEW);
            }
            if (bookEntry.getMobi() != null) {
                File bookData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".mobi");
                Files.write(bookData.toPath(), bookEntry.getMobi(), StandardOpenOption.CREATE_NEW);
            }
            File coverData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".jpg");
            Files.write(coverData.toPath(), bookEntry.getCover(), StandardOpenOption.CREATE_NEW);

            File metaDataFile = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".json");
            BookMetaData metaData = new BookMetaData(bookEntry.getAuthor(), bookEntry.getTitle(),
                    bookEntry.getIsbn(), bookEntry.getPublisher(), bookEntry.getDescription(),
                    bookEntry.getLanguage(), bookEntry.getReleaseDate(), bookEntry.getMimeType(),
                    bookEntry.getUploadDate(), bookEntry.getViewed(), bookEntry.getShared());
            gson.toJson(metaData);
            Files.write(metaDataFile.toPath(), gson.toJson(metaData).getBytes(), StandardOpenOption.CREATE_NEW);
        }

    }

    if (response.getResults().getNumFound() > offset) {
        exportBatchWise(server, exportFolder, batchSize, offset + batchSize, gson);
    }

}

From source file:org.ballerinalang.test.packaging.ImportModuleTestCase.java

/**
 * Importing installed modules from both normal sources and test sources.
 *
 * @throws BallerinaTestException When an error occurs executing the command.
 *//*from  ww w  .  j a v  a 2  s  .c o m*/
@Test(description = "Test importing installed modules in test sources")
public void testResolveImportsInBoth() throws BallerinaTestException, IOException {
    Path projPath = tempProjectDirectory.resolve("fourthProj");
    Files.createDirectories(projPath);

    FileUtils.copyDirectory(
            Paths.get((new File("src/test/resources/import-in-both")).getAbsolutePath()).toFile(),
            projPath.toFile());
    Files.createDirectories(projPath.resolve(".ballerina"));

    // ballerina install abc
    balClient.runMain("install", new String[] { "mod2" }, envVariables, new String[] {}, new LogLeecher[] {},
            projPath.toString());

    // Delete module 'abc' from the project
    PackagingTestUtils.deleteFiles(projPath.resolve("mod2"));
    PackagingTestUtils.deleteFiles(projPath.resolve(".ballerina").resolve("repo"));

    // Rename org-name to "natasha" in Ballerina.toml
    Path tomlFilePath = projPath.resolve("Ballerina.toml");
    String content = "[project]\norg-name = \"natasha\"\nversion = \"1.0.0\"\n";
    Files.write(tomlFilePath, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);

    // Module manny/mod2 will be picked from home repository since it was installed before
    balClient.runMain("build", new String[] {}, envVariables, new String[] {}, new LogLeecher[] {},
            projPath.toString());

    Assert.assertTrue(Files.exists(projPath.resolve(".ballerina").resolve("repo").resolve("natasha")
            .resolve("mod1").resolve("1.0.0").resolve("mod1.zip")));

    LogLeecher fLeecher = new LogLeecher("Hello Manny !! I got a message --> 100");
    balClient.runMain("test", new String[] { "mod1" }, envVariables, new String[] {},
            new LogLeecher[] { fLeecher }, projPath.toString());
    fLeecher.waitForText(3000);

    LogLeecher sLeecher = new LogLeecher("Hello Manny !! I got a message --> 100 <---->244");
    balClient.runMain("run", new String[] { "mod1" }, envVariables, new String[] {},
            new LogLeecher[] { sLeecher }, projPath.toString());
    sLeecher.waitForText(3000);
}

From source file:org.epics.archiverappliance.TomcatSetup.java

/**
 * @param testName//from ww w. j av  a2 s .  c o  m
 * @param applianceName
 * @param port
 * @param startupPort
 * @return Returns the CATALINA_BASE for this instance
 * @throws IOException
 */
private File makeTomcatFolders(String testName, String applianceName, int port, int startupPort)
        throws IOException {
    File testFolder = new File("tomcat_" + testName);
    assert (testFolder.exists());
    File workFolder = new File(testFolder, applianceName);
    assert (workFolder.mkdir());

    File webAppsFolder = new File(workFolder, "webapps");
    assert (webAppsFolder.mkdir());
    File logsFolder = new File(workFolder, "logs");
    assert (logsFolder.mkdir());
    FileUtils.copyFile(new File("log4j.properties"), new File(logsFolder, "log4j.properties"));
    File tempFolder = new File(workFolder, "temp");
    tempFolder.mkdir();

    logger.debug("Copying the webapps wars to " + webAppsFolder.getAbsolutePath());
    FileUtils.copyFile(new File("../mgmt.war"), new File(webAppsFolder, "mgmt.war"));
    FileUtils.copyFile(new File("../retrieval.war"), new File(webAppsFolder, "retrieval.war"));
    FileUtils.copyFile(new File("../etl.war"), new File(webAppsFolder, "etl.war"));
    FileUtils.copyFile(new File("../engine.war"), new File(webAppsFolder, "engine.war"));

    File confOriginal = new File(System.getenv("TOMCAT_HOME"), "conf_original");
    File confFolder = new File(workFolder, "conf");
    logger.debug("Copying the config from " + confOriginal.getAbsolutePath() + " to "
            + confFolder.getAbsolutePath());
    if (!confOriginal.exists()) {
        throw new IOException(
                "For the tomcat tests to work, we expect that when you extract the tomcat distrbution to "
                        + System.getenv("TOMCAT_HOME")
                        + ", you copy the pristine conf folder to a folder called conf_original. This folder "
                        + confOriginal.getAbsolutePath() + " does not seem to exist.");
    }
    // We expect that when you set up TOMCAT_HOME, 
    FileUtils.copyDirectory(confOriginal, confFolder);

    // We then replace the server.xml with one we generate.
    // TomcatSampleServer.xml is a simple MessageFormat template with entries for 
    // 0) server http port
    // 1) server startup port
    String serverXML = new String(
            Files.readAllBytes(Paths.get("./src/test/org/epics/archiverappliance/TomcatSampleServer.xml")));
    String formattedServerXML = MessageFormat.format(serverXML, port, startupPort);
    Files.write(Paths.get(confFolder.getAbsolutePath(), "server.xml"), formattedServerXML.getBytes(),
            StandardOpenOption.TRUNCATE_EXISTING);
    logger.debug("Done generating server.xml");

    return workFolder;
}

From source file:org.apache.kudu.client.MiniKdc.java

private void createKdcConf() throws IOException {
    List<String> contents = ImmutableList.of("[kdcdefaults]", "   kdc_ports = " + options.port,

            "[realms]", options.realm + " = {", "   acl_file = " + options.dataRoot.resolve("kadm5.acl"),
            "   admin_keytab = " + options.dataRoot.resolve("kadm5.keytab"),
            "   database_name = " + options.dataRoot.resolve("principal"),
            "   key_stash_file = " + options.dataRoot.resolve(".k5." + options.realm),
            "   max_renewable_life = 7d 0h 0m 0s", "}");

    Files.write(options.dataRoot.resolve("kdc.conf"), contents, Charsets.UTF_8);
}

From source file:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.java

private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize,
        ChartHistoMovingAverage histoAverage, ChartHistoTimeSpan histoPeriod, Integer intradayWidth,
        Integer intradayHeight) {

    Preconditions.checkNotNull(stock, "stock must not be null!");
    Preconditions.checkNotNull(type, "ChartType must not be null!");

    String guid = AuthenticationUtil.getPrincipal().getUsername();
    SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
    if (socialUser == null) {
        return;/*from ww w  . ja  v a 2 s  . c om*/
    }
    String token = socialUser.getAccessToken();
    Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

    if (connection != null) {
        byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type,
                histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
        String imageName = stock.getId().toLowerCase() + "_" + type.name().toLowerCase() + "_"
                + formattedDateTime + ".png";
        String pathToYahooPicture = env.getProperty("user.home").concat(env.getProperty("pictures.yahoo.path"))
                .concat(File.separator + imageName);

        try {
            Path newPath = Paths.get(pathToYahooPicture);
            Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new Error("Storage of " + pathToYahooPicture + " failed", e);
        }

        ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth,
                intradayHeight, pathToYahooPicture);
        chartStockRepository.save(chartStock);
    }
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java

private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize,
        ChartHistoMovingAverage histoAverage, ChartHistoTimeSpan histoPeriod, Integer intradayWidth,
        Integer intradayHeight) {

    Preconditions.checkNotNull(stock, "stock must not be null!");
    Preconditions.checkNotNull(type, "ChartType must not be null!");

    String guid = AuthenticationUtil.getPrincipal().getUsername();
    String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken();
    ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid);
    Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

    if (connection != null) {
        byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type,
                histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
        String imageName = stock.getId().toLowerCase() + "_" + type.name().toLowerCase() + "_"
                + formattedDateTime + ".png";
        String pathToYahooPicture = env.getProperty("pictures.yahoo.path").concat(File.separator + imageName);

        try {/*from  w  w  w . ja v  a 2 s.  c o  m*/
            Path newPath = Paths.get(pathToYahooPicture);
            Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new Error("Storage of " + pathToYahooPicture + " failed", e);
        }

        ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth,
                intradayHeight, pathToYahooPicture);
        chartStockRepository.save(chartStock);
    }
}

From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java

@Test
public void testTailLogMultipleDirs() throws Exception {
    File testDataDir1 = new File("target", UUID.randomUUID().toString());
    File testDataDir2 = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir1.mkdirs());
    Assert.assertTrue(testDataDir2.mkdirs());
    Files.write(new File(testDataDir1, "log1.txt").toPath(), Arrays.asList("Hello"), UTF8);
    Files.write(new File(testDataDir2, "log2.txt").toPath(), Arrays.asList("Hola"), UTF8);

    FileInfo fileInfo1 = new FileInfo();
    fileInfo1.tag = "tag1";
    fileInfo1.fileFullPath = testDataDir1.getAbsolutePath() + "/log1.txt";
    fileInfo1.fileRollMode = FileRollMode.REVERSE_COUNTER;
    fileInfo1.firstFile = "";
    fileInfo1.patternForToken = "";
    FileInfo fileInfo2 = new FileInfo();
    fileInfo2.tag = "";
    fileInfo2.fileFullPath = testDataDir2.getAbsolutePath() + "/log2.txt";
    fileInfo2.fileRollMode = FileRollMode.REVERSE_COUNTER;
    fileInfo2.firstFile = "";
    fileInfo2.patternForToken = "";

    FileTailConfigBean conf = new FileTailConfigBean();
    conf.dataFormat = DataFormat.TEXT;/*from  www. ja  v a 2s .c o  m*/
    conf.multiLineMainPattern = "";
    conf.batchSize = 25;
    conf.maxWaitTimeSecs = 1;
    conf.fileInfos = Arrays.asList(fileInfo1, fileInfo2);
    conf.postProcessing = PostProcessingOptions.NONE;
    conf.dataFormatConfig.textMaxLineLen = 1024;

    FileTailSource source = new FileTailSource(conf, SCAN_INTERVAL);
    SourceRunner runner = new SourceRunner.Builder(FileTailDSource.class, source).addOutputLane("lane")
            .addOutputLane("metadata").build();
    runner.runInit();
    try {
        Date now = new Date();
        Thread.sleep(10);
        StageRunner.Output output = runner.runProduce(null, 1000);
        Assert.assertEquals(2, output.getRecords().get("lane").size());
        Record record = output.getRecords().get("lane").get(0);
        Assert.assertEquals("Hello", record.get("/text").getValueAsString());
        Assert.assertEquals("tag1", record.getHeader().getAttribute("tag"));
        Assert.assertEquals(fileInfo1.fileFullPath, record.getHeader().getAttribute("file"));
        record = output.getRecords().get("lane").get(1);
        Assert.assertEquals("Hola", record.get("/text").getValueAsString());
        Assert.assertNull(record.getHeader().getAttribute("tag"));
        Assert.assertEquals(fileInfo2.fileFullPath, record.getHeader().getAttribute("file"));

        Assert.assertEquals(2, output.getRecords().get("metadata").size());
        Record metadata = output.getRecords().get("metadata").get(0);
        Assert.assertEquals(new File(fileInfo1.fileFullPath).getAbsolutePath(),
                metadata.get("/fileName").getValueAsString());
        Assert.assertEquals("START", metadata.get("/event").getValueAsString());
        Assert.assertTrue(now.compareTo(metadata.get("/time").getValueAsDate()) < 0);
        Assert.assertTrue(metadata.has("/inode"));
        metadata = output.getRecords().get("metadata").get(1);
        Assert.assertEquals(new File(fileInfo2.fileFullPath).getAbsolutePath(),
                metadata.get("/fileName").getValueAsString());
        Assert.assertEquals("START", metadata.get("/event").getValueAsString());
        Assert.assertTrue(now.compareTo(metadata.get("/time").getValueAsDate()) < 0);
        Assert.assertTrue(metadata.has("/inode"));
    } finally {
        runner.runDestroy();
    }
}

From source file:org.ballerinalang.test.packaging.ModuleBuildTestCase.java

@Test(description = "Test building a module which has xml content in the test package")
public void testBuildWithXML() throws BallerinaTestException, IOException {
    Path projectPath = tempProjectDirectory.resolve("sixthTestProject");
    initProject(projectPath, SINGLE_PKG_PROJECT_OPTS);

    // Replace the content of the test file
    String testContent = "import ballerina/test;\n" + "import ballerina/io;\n" + "\n"
            + "xmlns \"http://ballerina.com/aa\" as ns0;\n" + "\n" + "# Test function\n" + "\n"
            + "@test:Config\n" + "function testFunction () {\n" + "    io:println(\"I'm in test function!\");\n"
            + "    test:assertTrue(true , msg = \"Failed!\");\n" + "\n"
            + "    xmlns \"http://ballerina.com/bb\" as ns1;\n"
            + "    xmlns \"http://ballerina.com/default\";\n" + "\n" + "    io:println(ns0:foo);\t\n" + "}\n";

    Files.write(projectPath.resolve("foo").resolve("tests").resolve("main_test.bal"), testContent.getBytes(),
            StandardOpenOption.TRUNCATE_EXISTING);

    balClient.runMain("build", new String[0], envVariables, new String[0], new LogLeecher[] {},
            projectPath.toString());/*from   www. j  a  v  a2  s.c om*/

    Path genPkgPath = Paths.get(ProjectDirConstants.DOT_BALLERINA_DIR_NAME,
            ProjectDirConstants.DOT_BALLERINA_REPO_DIR_NAME, ORG_NAME, "foo", VERSION);
    Assert.assertTrue(Files.exists(projectPath.resolve(genPkgPath).resolve("foo.zip")));
    Assert.assertTrue(Files.exists(projectPath.resolve("target").resolve("foo.balx")));
}

From source file:com.alibaba.jstorm.yarn.container.Executor.java

/**
 * set local conf/*from   www. j  a va 2 s . c  om*/
 *
 * @param key
 * @param value
 * @return
 */
public boolean setJstormConf(String key, String value) {
    //todo: how to set conf from a signal
    // could pull configuration file from nimbus
    String line = " " + key + ": " + value;
    try {
        Files.write(Paths.get("deploy/jstorm/conf/storm.yaml"), line.getBytes(), StandardOpenOption.APPEND);

    } catch (IOException e) {
        LOG.error(e);
        return false;
    }
    return true;
}