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:nl.tranquilizedquality.itest.cargo.AbstractGlassfishContainerUtil.java

/**
 * Complete the Glassfish configuration.
 *
 * @throws IOException/*w  w  w  . ja va  2  s. c  o  m*/
 *
 */
private void completeGlassfishConfiguration() throws IOException {

    // FIXME: Complete setting also the port to the value
    // ${cargo.server.port}

    // We need to append the java home value to the env script.
    final String operatingSystem = System.getProperty("os.name");
    File destFile = null;
    if (operatingSystem != null && operatingSystem.startsWith("Windows")) {

        destFile = new File(containerHome + "/config/asenv.bat");

        final List readLines = FileUtils.readLines(destFile);
        readLines.add("set AS_JAVA=" + System.getProperty("java.home"));
        FileUtils.writeLines(destFile, readLines);

    } else {
        destFile = new File(containerHome + "/config/asenv.conf");

        final List readLines = FileUtils.readLines(destFile);
        readLines.add("AS_JAVA=\"" + System.getProperty("java.home") + "\"");
        FileUtils.writeLines(destFile, readLines);

        // There is a problem in Linux executing the file... probably is a
        // bug in the glassfish plugin

        // We must use the Runtime call (not really portable) since the
        // setExecutable method in the File class is only available from
        // Java 6
        // File executable = new File("/tmp/glassfish/bin/asadmin");
        // executable.setExecutable(true);
        Runtime.getRuntime().exec("chmod 754 " + "/tmp/glassfish/bin/asadmin");

    }
}

From source file:ome.formats.utests.IniFileLoaderTest.java

@Test
public void testFlexReaderServerMapUNC() throws Exception {
    FileUtils.writeLines(temporaryFile, Arrays.asList("[FlexReaderServerMaps]",
            "CIA-1=\\\\\\\\hostname1\\\\path1;\\\\\\\\hostname1\\\\path2"));
    Preferences test = new IniFile(temporaryFile, Mode.RW);
    Preferences maps = test.node("FlexReaderServerMaps");
    Map<String, List<String>> parsedMaps = ini.parseFlexMaps(maps);
    assertEquals(1, parsedMaps.size());/*from  ww w  . ja  va  2s .  co  m*/
    List<String> serverPaths = parsedMaps.get("CIA-1");
    assertEquals(2, serverPaths.size());
    assertEquals("\\\\hostname1\\path1", serverPaths.get(0));
    assertEquals("\\\\hostname1\\path2", serverPaths.get(1));
}

From source file:ome.formats.utests.IniFileLoaderTest.java

@Test
public void testFlexReaderServerMapUnix() throws Exception {
    FileUtils.writeLines(temporaryFile, Arrays.asList("[FlexReaderServerMaps]", "CIA-1=/mnt/path1;/mnt/path2"));
    Preferences test = new IniFile(temporaryFile, Mode.RW);
    Preferences maps = test.node("FlexReaderServerMaps");
    Map<String, List<String>> parsedMaps = ini.parseFlexMaps(maps);
    assertEquals(1, parsedMaps.size());/*  ww w .j  av a 2  s  . c  om*/
    List<String> serverPaths = parsedMaps.get("CIA-1");
    assertEquals(2, serverPaths.size());
    assertEquals("/mnt/path1", serverPaths.get(0));
    assertEquals("/mnt/path2", serverPaths.get(1));
}

From source file:ome.formats.utests.IniFileLoaderTest.java

@Test
public void testDuplicatedSections() throws Exception {
    FileUtils.writeLines(temporaryFile, Arrays.asList("[Section]", "A=1", "[Section]", "A=2"));
    Preferences test = new IniFile(temporaryFile, Mode.RW);
    String a1 = test.node("Section").get("A", "missing");
    assertEquals("2", a1);
}

From source file:ome.formats.utests.IniFileLoaderTest.java

@Test
public void testDuplicatedSections2() throws Exception {
    FileUtils.writeLines(temporaryFile, Arrays.asList("[Section]", "[Section]", "A=1"));
    Preferences test = new IniFile(temporaryFile, Mode.RW);
    String a1 = test.node("Section").get("A", "missing");
    assertEquals("1", a1);
}

From source file:omero.util.test.TempFileManagerTest.java

@Test
public void testUsingThePath() throws IOException {
    File p = TempFileManager.create_path("write", ".txt");
    FileUtils.writeLines(p, Arrays.asList("hi"));
    String hi = FileUtils.readFileToString(p).trim();
    assertEquals("hi", hi);
}

From source file:omero.util.test.TempFileManagerTest.java

@Test
public void testUsingThePathAndAFile() throws IOException {
    File p = TempFileManager.create_path("write", ".txt");
    FileUtils.writeLines(p, Arrays.asList("hi"));
    File f = new File(p.getAbsolutePath());
    String hi = FileUtils.readFileToString(f).trim();
    assertEquals("hi", hi);
}

From source file:org.agilereview.fileparser.FileParser.java

/**
 * Adds tags with the given tag id to the document from line selStartLine to selEndLine. If there are conflicts with comments in the start line or
 * end line, the comment will be expanded to the next greater valid region.
 * @param tagId tag id to be inserted/*from w w w.ja  va2  s.c  o  m*/
 * @param startLine start line of the comment
 * @param endLine end line of the comment
 * @throws IOException if the file could not be read or written
 * @author Malte Brunnlieb (18.05.2014)
 */
public void addTags(String tagId, int startLine, int endLine) throws IOException {
    LOG.debug("Add tags for comment with tagId '{}' to start line {} / end line {}", tagId, startLine, endLine);

    startLine--;
    endLine--;

    CommentTagBuilder tagBuilder = new CommentTagBuilder(tags[0], tags[1]);

    boolean startLineInserted = false, endLineInserted = false;
    int origSelStartLine = startLine;
    boolean[] significantlyChanged = new boolean[] { false, false };

    // TODO maybe better work on a stream than loading the whole file in memory
    //        LineIterator it = FileUtils.lineIterator(testResource);
    //        new ArrayDeque<>(5);
    //        while(it.hasNext()) {
    //            String line = it.nextLine();
    //            
    //        }
    List<String> lines = FileUtils.readLines(file);

    // check if selection needs to be adapted
    int[] newLines = computeSelectionAdapations(lines, startLine, endLine);
    if (newLines[0] != -1 || newLines[1] != -1) {
        LOG.debug(
                "Comment starts and/or ends within a source comment -> adapt lines to start line {} / end line {}",
                newLines[0] + 1, newLines[1] + 1);
        // adapt starting line if necessary
        if (newLines[0] != -1) {
            //                 insert new line if code is in front of javadoc / multi line comments
            String line = lines.get(newLines[0]);
            if (!line.trim().isEmpty()) {
                lines.add(newLines[0] + 1, "");
                startLine = newLines[0] + 1;
                startLineInserted = true;
            } else {
                startLine = newLines[0];
            }

            // only inform the user about these adaptations if he did not select the whole javaDoc
            if (origSelStartLine - 1 != startLine) {
                significantlyChanged[0] = true;
            }
        }

        // adapt ending line if necessary
        // add a new line if a line was inserted before
        if (newLines[1] != -1) {
            endLine = newLines[1] + (startLineInserted ? 1 : 0);
            significantlyChanged[1] = true;
        } else {
            endLine += (startLineInserted ? 1 : 0);
        }
    }

    // add new line if start line is last line of javaDoc
    int[] adaptionLines = checkForCodeComment(lines, startLine);
    if (adaptionLines[0] != -1 && !lines.get(adaptionLines[0]).trim().isEmpty()) {
        lines.add(startLine + 1, "");
        startLine++;
        endLine++;
        startLineInserted = true;
        significantlyChanged[0] = true;
    }

    // add new line if end line is last line of javaDoc
    adaptionLines = checkForCodeComment(lines, endLine);
    if (adaptionLines[1] != -1 && lineContains(lines.get(adaptionLines[1]), "/**")) {
        String line = lines.get(endLine + 1);
        if (!line.trim().isEmpty()) {
            lines.add(endLine + 1, "");
            endLine++;
            endLineInserted = true;
            significantlyChanged[1] = true;
        }
    }

    if (startLine == endLine) {
        LOG.debug("Comment is single-line comment.");
        // Only one line is selected
        // Write tag -> get start+end-tag for current file-ending, insert into file
        tagBuilder.isSingleLine();
        if (startLineInserted || endLineInserted) {
            tagBuilder.cleanupLineWithCommentRemoval(true);
        } else {
            tagBuilder.cleanupLineWithCommentRemoval(false);
        }
        String line = lines.remove(startLine);
        line += tagBuilder.buildTag(tagId);
        lines.add(startLine, line);
    } else {
        LOG.debug("Comment is multi-line comment.");
        // Write tags -> get tags for current file-ending, insert second tag, insert first tag
        tagBuilder.isMultilineEndTag();
        if (endLineInserted) {
            tagBuilder.cleanupLineWithCommentRemoval(true);
        } else {
            tagBuilder.cleanupLineWithCommentRemoval(false);
        }
        String line = lines.remove(endLine);
        line += tagBuilder.buildTag(tagId);
        lines.add(endLine, line);

        tagBuilder.isMultilineStartTag();
        if (startLineInserted) {
            tagBuilder.cleanupLineWithCommentRemoval(true);
        } else {
            tagBuilder.cleanupLineWithCommentRemoval(false);
        }
        line = lines.remove(startLine);
        line += tagBuilder.buildTag(tagId);
        lines.add(startLine, line);
    }

    LOG.debug("Write file back.");
    FileUtils.writeLines(file, lines);

    //        parseInput();

    // ##########################################################

    //        try (FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(new FileReader(file));) {
    //            StringBuilder contents = new StringBuilder();
    //            boolean isMultiLineComment = (startLine != endLine);
    //            Matcher matcher;
    //            
    //            String line;
    //            int lineNr = 0;
    //            while ((line = reader.readLine()) != null) {
    //                lineNr++;
    //                matcher = tagPattern.matcher(line);
    //                if (lineNr == startLine) {
    //                    if (isMultiLineComment) {
    //                        tagBuilder.isMultilineStartTag().
    //                    } else {
    //                        
    //                    }
    //                }
    //                if (lineNr != 0) {
    //                    contents.append(newline);
    //                }
    //                contents.append(line);
    //            }
    //            
    //            // write the new String with the replaced line OVER the same file
    //            FileOutputStream output = new FileOutputStream(file);
    //            output.write(contents.toString().getBytes());
    //            output.close();
    //        } catch (Exception e) {
    //            // TODO: handle exception
    //        }
}

From source file:org.agilereview.fileparser.FileParser.java

/**
 * Removes all tags matching the given tag pattern
 * @param tagPattern tags to be removed//from w ww  .ja v  a  2s. c om
 * @param groupIncrement value to increment the group value for retrieving the line removal marker
 * @throws IOException if the file could not be read or written
 * @author Malte Brunnlieb (25.05.2014)
 */
private void removeTags(Pattern tagPattern, int groupIncrement) throws IOException {
    String removalCharacter = ParserProperties.newInstance()
            .getProperty(ParserProperties.LINE_REMOVAL_MARKER_SIGN);
    Matcher matcher;
    String line;
    List<String> lines = new LinkedList<String>();
    try (FileReader fileReader = new FileReader(file);
            BufferedReader reader = new BufferedReader(new FileReader(file));) {
        while ((line = reader.readLine()) != null) {
            matcher = tagPattern.matcher(line);
            boolean removeLine = false;
            if (matcher.find()) {
                if (removalCharacter.equals(matcher.group(3 + groupIncrement))) {
                    LOG.debug("Tag is marked such that the line should be removed if empty");
                    String newLine = matcher.replaceAll("");
                    if (newLine.trim().isEmpty()) {
                        removeLine = true;
                        LOG.debug("Line removed");
                    }
                }
            }
            if (!removeLine)
                lines.add(matcher.replaceAll(""));
        }
    }
    FileUtils.writeLines(file, lines);
}

From source file:org.apache.crunch.lib.ShardIT.java

@Test
public void testShard() throws Exception {
    File inDir = tempDir.getFile("in");
    FileUtils.writeLines(new File(inDir, "part1"), ImmutableList.of("part1", "part1"));
    FileUtils.writeLines(new File(inDir, "part2"), ImmutableList.of("part2"));
    Pipeline pipeline = new MRPipeline(ShardIT.class);
    PCollection<String> in = pipeline.read(From.textFile(inDir.getPath()));
    // We can only test on 1 shard here, as local MR does not support multiple reducers.
    PCollection<String> out = Shard.shard(in, 1);
    assertEquals(ImmutableMultiset.copyOf(out.materialize()), ImmutableMultiset.of("part1", "part1", "part2"));
}