Example usage for org.apache.commons.io FileUtils writeLines

List of usage examples for org.apache.commons.io FileUtils writeLines

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeLines.

Prototype

public static void writeLines(File file, Collection lines) throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to the specified File line by line.

Usage

From source file:org.exnebula.bootstrap.TestHelper.java

public static void makeConfigFile(String endpoint, String targetJarPath) throws IOException {
    FileUtils.writeLines(getConfigFileAssociatedWithBoot(),
            Arrays.asList("ep=" + endpoint, "cp=" + targetJarPath));
}

From source file:org.gradle.nativeplatform.internal.modulemap.GenerateModuleMapFile.java

public static void generateFile(File moduleMapFile, String moduleName, List<String> publicHeaderDirs) {
    List<String> lines = Lists.newArrayList("module " + moduleName + " {");
    List<String> validHeaderDirs = filter(publicHeaderDirs, new Spec<String>() {
        @Override/*w  w w .  ja v  a 2 s.c o  m*/
        public boolean isSatisfiedBy(String path) {
            return new File(path).exists();
        }
    });
    lines.addAll(collect(validHeaderDirs, new Transformer<String, String>() {
        @Override
        public String transform(String path) {
            return "\tumbrella \"" + path + "\"";
        }
    }));
    lines.add("\texport *");
    lines.add("}");
    try {
        Files.createParentDirs(moduleMapFile);
        FileUtils.writeLines(moduleMapFile, lines);
    } catch (IOException e) {
        throw new UncheckedIOException("Could not generate a module map for " + moduleName, e);
    }
}

From source file:org.gradle.nativeplatform.toolchain.internal.PCHUtils.java

public static void generatePCHFile(List<String> headers, File headerFile) {
    if (!headerFile.getParentFile().exists()) {
        headerFile.getParentFile().mkdirs();
    }/*w ww  .  j a  v  a2 s  .com*/

    try {
        FileUtils.writeLines(headerFile, CollectionUtils.collect(headers, new Transformer<String, String>() {
            @Override
            public String transform(String header) {
                if (header.startsWith("<")) {
                    return "#include ".concat(header);
                } else {
                    return "#include \"".concat(header).concat("\"");
                }
            }
        }));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.gradle.nativeplatform.toolchain.internal.PrefixHeaderFileGeneratorUtil.java

public static void generatePCHFile(Set<String> headers, File headerFile) {
    if (!headerFile.getParentFile().exists()) {
        headerFile.getParentFile().mkdirs();
    }//from  w w  w . ja  v a  2s .  c om

    try {
        FileUtils.writeLines(headerFile,
                CollectionUtils.collect(CollectionUtils.toList(headers), new Transformer<String, String>() {
                    @Override
                    public String transform(String header) {
                        if (header.startsWith("<")) {
                            return "#include ".concat(header);
                        } else {
                            return "#include \"".concat(header).concat("\"");
                        }
                    }
                }));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.gridgain.client.impl.GridClientPropertiesConfigurationSelfTest.java

/**
 * Uncomment properties.//from  w  ww. j a  va  2 s  . c  om
 *
 * @param url Source to uncomment client properties for.
 * @return Temporary file with uncommented client properties.
 * @throws IOException In case of IO exception.
 */
private File uncommentProperties(URL url) throws IOException {
    InputStream in = url.openStream();

    assertNotNull(in);

    LineIterator it = IOUtils.lineIterator(in, "UTF-8");
    Collection<String> lines = new ArrayList<>();

    while (it.hasNext())
        lines.add(it.nextLine().replace("#gg.client.", "gg.client."));

    GridUtils.closeQuiet(in);

    File tmp = File.createTempFile(UUID.randomUUID().toString(), "properties");

    tmp.deleteOnExit();

    FileUtils.writeLines(tmp, lines);

    return tmp;
}

From source file:org.grycap.gpf4med.URLUtilsTest.java

@Test
public void test() {
    System.out.println("URLUtilsTest.test()");
    try {//from w  w w.j  a  v  a 2 s . co  m
        // load index
        final String[] validLines = new String[] { "file:///path/to/local-file-system",
                "http://www.google.com/index.html", "https://github.com/index.html # GitHub" };
        final String[] invalidLines = new String[] { "/path/to/local-file-system",
                "invalid_protocol://www.google.com/index.html" };
        final String[] commentLines = new String[] { "#file:///path/to/local-file-system",
                " #  http://www.google.com/index.html", "#file:///path/to/local-file-system",
                " #  http://www.google.com/index.html", "   #file:///path/to/local-file-system" };
        final List<String> linesList = new ArrayList<String>();
        linesList.addAll(Arrays.asList(validLines));
        linesList.addAll(Arrays.asList(invalidLines));
        linesList.addAll(Arrays.asList(commentLines));
        final String indexFilename = FilenameUtils.concat(TEST_OUTPUT_DIR, "index.txt");
        FileUtils.writeLines(new File(indexFilename), linesList);
        final URL[] urls = URLUtils.readIndex(new File(indexFilename).toURI().toURL());
        assertThat("URLs is not null", urls, notNullValue());
        assertThat("number of readed URLs coincides", urls.length, equalTo(validLines.length));
        for (final String line : validLines) {
            boolean found = false;
            final String target = new StringTokenizer(line).nextToken();
            for (int i = 0; i < urls.length && !found; i++) {
                final String query = (!URLUtils.isFileProtocol(urls[i]) ? urls[i].toString()
                        : URLUtils.FILE + "://" + urls[i].getPath());
                if (query.equals(target)) {
                    found = true;
                }
            }
            assertThat("a valid URL was found in the index: " + line, found);
        }
        // parse URL
        final String[][] paths = { { "file:///foo", "/foo" }, { "/foo//", "/foo/" }, { "/foo/./", "/foo/" },
                { "/foo/../bar", "/bar" }, { "/foo/../bar/", "/bar/" }, { "/foo/../bar/../baz", "/baz" },
                { "//foo//./bar", "/foo/bar" }, { "/../", null },
                { "../foo", FilenameUtils.concat(System.getProperty("user.dir"), "../foo") },
                { "foo/bar/..", FilenameUtils.concat(System.getProperty("user.dir"), "foo/bar/..") },
                { "foo/../../bar", FilenameUtils.concat(System.getProperty("user.dir"), "foo/../../bar") },
                { "foo/../bar", FilenameUtils.concat(System.getProperty("user.dir"), "foo/../bar") },
                { "//server/foo/../bar", "/server/bar" }, { "//server/../bar", null },
                { "C:\\foo\\..\\bar", "/bar" }, { "C:\\..\\bar", null },
                { "~/foo/../bar/", FilenameUtils.concat(System.getProperty("user.home"), "foo/../bar/") },
                { "~/../bar", FilenameUtils.concat(System.getProperty("user.home"), "../bar") },
                { "http://localhost", null } };
        for (int i = 0; i < paths.length; i++) {
            URL url = null;
            try {
                url = URLUtils.parseURL(paths[i][0]);
                System.out.println("PATH='" + paths[i][0] + "', URL='" + (url != null ? url.toString() : "NULL")
                        + "', EXPECTED='" + paths[i][1] + "'");
                assertThat("URL is not null", url, notNullValue());
                if (URLUtils.isFileProtocol(url)) {
                    final File file = FileUtils.toFile(url);
                    assertThat("file is not null", file, notNullValue());
                    assertThat("file name coincides",
                            FilenameUtils.normalizeNoEndSeparator(file.getCanonicalPath(), true)
                                    .equals(FilenameUtils.normalizeNoEndSeparator(paths[i][1], true)));
                }
            } catch (IOException ioe) {
                if (paths[i][1] != null) {
                    throw ioe;
                } else {
                    System.out.println("PATH='" + paths[i][0] + "' thrown the expected exception");
                }
            }
        }
        // validate URL
        assertThat("valid URL", URLUtils.isValid("http://www.google.com", true));
        assertThat("valid URL", !URLUtils.isValid("http://invalidURL^$&%$&^", true));
        assertThat("valid URL", URLUtils.isValid("http://example.com/file[/].html", false));
        assertThat("valid URL", !URLUtils.isValid("http://example.com/file[/].html", true));
    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("URLUtilsTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("URLUtilsTest.test() has finished");
    }
}

From source file:org.jboss.arquillian.android.drone.impl.SelendroidRebuilder.java

/**
 * Replaces AndroidManifest.xml file which contains default testapp base package to use the propper one
 *
 * @param toBeReplaced/*from   w  ww .  j  a  v  a 2 s.c o m*/
 * @param finalManifest
 */
@SuppressWarnings("unchecked")
private void filterManifestFile(File toBeReplaced, File finalManifest) {
    try {
        List<String> oldManifest = FileUtils.readLines(toBeReplaced);
        List<String> finalManifestList = Replacer.replace(oldManifest, "org\\.openqa\\.selendroid\\.testapp",
                applicationBasePackage);
        FileUtils.writeLines(finalManifest, finalManifestList);
    } catch (IOException e) {
        logger.severe(e.getMessage());
    }
}

From source file:org.jcvi.ometa.engine.LoadingEngine.java

public void batchLoad() throws Exception {
    String userName = usage.getUsername();
    String passWord = usage.getPassword();
    String serverUrl = usage.getServerUrl();

    String eventFileName = usage.getInputFilename();
    String eventName = usage.getEventName();
    String projectName = usage.getProjectName();
    String outputPath = usage.getOutputLocation();

    int batchSizeInt = 1;
    String batchSize = usage.getBatchSize();
    if (batchSize != null && !batchSize.isEmpty()) {
        batchSizeInt = Integer.parseInt(batchSize);
    }//w  w w .  ja  v a 2 s  .c o  m

    File eventFile = new File(eventFileName);

    Long timeStamp = new Date().getTime();
    File logFile = new File(outputPath + File.separator + "ometa.log");
    FileWriter logWriter = new FileWriter(logFile, false);

    int successCount = 0;
    File processedFile = new File(outputPath + File.separator + "ometa_processed.csv");
    FileWriter processedWriter = new FileWriter(processedFile, false);
    int failedCount = 0;
    File failedFile = new File(outputPath + File.separator + "ometa_failed.csv");
    FileWriter failedWriter = new FileWriter(failedFile, false);

    // Must break this file up, and deposit it into a temporary output directory.
    String userBase = System.getProperty("user.home");
    ScratchUtils.setScratchBaseLocation(userBase + "/" + Constants.SCRATCH_BASE_LOCATION);
    File scratchLoc = ScratchUtils.getScratchLocation(timeStamp, "LoadingEngine__" + eventFile.getName());

    int processedLineCount = 0;
    try {
        BeanWriter writer = new BeanWriter(serverUrl, userName, passWord);

        LineIterator lineIterator = FileUtils.lineIterator(eventFile);
        int lineCount = 0;

        String headerLine = null;
        while (lineIterator.hasNext()) {
            ++lineCount;
            String currLine = lineIterator.nextLine();

            if (lineCount == 1) {
                headerLine = currLine;
                processedWriter.write(currLine + "\n");
                failedWriter.write(currLine + "\n");
                continue;
            } else if (lineCount == 2 && (currLine.startsWith("#") || currLine.startsWith("\"#"))) { //skip comment line
                continue;
            } else {
                File singleEventFile = new File(scratchLoc.getAbsoluteFile() + File.separator + "temp.csv");
                List<String> lines = new ArrayList<String>(2);
                lines.add(headerLine);
                lines.add(currLine);
                FileUtils.writeLines(singleEventFile, lines);

                try {
                    String eventTarget = writer.writeEvent(singleEventFile, eventName, projectName, true);
                    logWriter.write(String.format("[%d] loaded event for %s\n", lineCount, eventTarget));
                    processedWriter.write(currLine + "\n");
                    successCount++;
                } catch (Exception ex) {
                    failedWriter.write(currLine + "\n");
                    logWriter.write(String.format("[%d] failed :\n", lineCount));
                    logWriter.write(ex.getMessage() + "\n");
                    failedCount++;
                }
                processedLineCount++;
            }
        }
    } catch (IOException ioe) {
        System.err.println("IOException: " + ioe.getMessage());
    } catch (Exception ex) {
        String exceptionString = ex.getCause() == null ? ex.getMessage() : ex.getCause().getMessage();
        logWriter.write(exceptionString);
        throw ex;
    } finally {
        if (scratchLoc != null && scratchLoc.exists()) {
            File cleanupDir = scratchLoc;
            String parentDirName = cleanupDir.getParentFile().getName();
            try {
                Long.parseLong(parentDirName);
                cleanupDir = cleanupDir.getParentFile();
            } catch (NumberFormatException nf) {
            }
            FileUtils.forceDelete(cleanupDir);
        }

        logWriter.close();
        processedWriter.close();
        failedWriter.close();
        System.out.printf("total: %d, processed: %d, failed: %d\n", processedLineCount, successCount,
                failedCount);
        System.out.println("log file: " + logFile.getAbsolutePath());
    }
}

From source file:org.jenkinsci.plugins.SemanticVersioning.test.ParserTests.java

protected void writeLinesToFile(String filename, Collection<String> lines) throws IOException {
    File file = new File(filename);
    if (file.exists()) {
        file.delete();/*w w w.  j  a  va 2s.  c om*/
    }
    file.setWritable(true);

    FileUtils.writeLines(file, lines);
}

From source file:org.kalypso.model.wspm.pdb.ui.internal.gaf.GafWriter.java

private void writeAdditionalLines(final File gafFile) throws IOException {
    if (m_additionalLines.isEmpty())
        return;//w w  w .  j a va 2  s.  c o m

    final String hykFilePath = gafFile.getAbsolutePath() + ".hyk"; //$NON-NLS-1$
    final File hykFile = new File(hykFilePath);

    FileUtils.writeLines(hykFile, m_additionalLines);
}