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

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

Introduction

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

Prototype

public static void writeLines(Collection lines, String lineEnding, Writer writer) throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to a Writer line by line, using the specified line ending.

Usage

From source file:org.ebayopensource.turmeric.eclipse.utils.io.PropertiesFileUtil.java

@SuppressWarnings("unchecked")
private static void accessProperty(InputStream input, OutputStream output, String[] keys,
        PropertyOperation operation, boolean autoclose) throws IOException {
    List<String> lines = new ArrayList<String>();
    List<String> result = new ArrayList<String>();
    try {//from   w  ww .  j  a  va 2  s . c  om
        lines = IOUtils.readLines(input);
    } finally {
        if (autoclose) {
            IOUtils.closeQuietly(input);
        }
    }
    try {
        for (String line : lines) {
            int offset = line.indexOf("=");
            if (line.trim().length() > 0 && offset > -1) {
                String originalKey = line.substring(0, offset).trim();
                String originalValue = line.substring(++offset);
                int index = ArrayUtils.indexOf(keys, originalKey);
                if (index > -1) {
                    String outputLine = operation.process(line, originalKey, originalValue);
                    if (outputLine != null) {
                        result.add(outputLine);
                    }
                } else {
                    result.add(line);
                }
            } else {
                result.add(line);
            }
        }
        if (output != null) {
            IOUtils.writeLines(result, null, output);
        }
    } finally {
        if (autoclose) {
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:org.ebayopensource.turmeric.eclipse.utils.io.PropertiesFileUtil.java

/**
 * Adds the property.//w  w w  .j  a  v  a2  s . c om
 *
 * @param input the input
 * @param output the output
 * @param properties the properties
 * @throws IOException Signals that an I/O exception has occurred.
 */
@SuppressWarnings("unchecked")
public static void addProperty(InputStream input, OutputStream output, Map<String, String> properties)
        throws IOException {
    List<String> sources = new ArrayList<String>();
    try {
        sources = IOUtils.readLines(input);
    } finally {
        IOUtils.closeQuietly(input);
    }
    try {
        for (String key : properties.keySet()) {
            String value = properties.get(key);
            sources.add(key + "=" + value);
        }
        IOUtils.writeLines(sources, null, output);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:org.eclipse.rdf4j.rio.RDFWriterTest.java

private void testPerformanceInternal(boolean storeParsedStatements) throws Exception {
    Model model = new LinkedHashModel();

    for (int i = 0; i < 10000; i++) {

        Value obj = potentialObjects.get(prng.nextInt(potentialObjects.size()));
        if (obj == litBigPlaceholder) {
            StringBuffer big = new StringBuffer();
            int len = 25000 + prng.nextInt(5000);
            for (int j = 0; j < len; j++) {
                big.append(((char) (32 + prng.nextInt(90))));
            }/*  w  w  w  .  j a  v a2  s. c  o m*/
            obj = vf.createLiteral(big.toString());
        }

        model.add(potentialSubjects.get(prng.nextInt(potentialSubjects.size())),
                potentialPredicates.get(prng.nextInt(potentialPredicates.size())), obj);
    }
    System.out.println("Test class: " + this.getClass().getName());
    System.out.println("Test statements size: " + model.size() + " (" + rdfWriterFactory.getRDFFormat() + ")");
    assertFalse("Did not generate any test statements", model.isEmpty());

    File testFile = tempDir
            .newFile("performancetest." + rdfWriterFactory.getRDFFormat().getDefaultFileExtension());

    FileOutputStream out = new FileOutputStream(testFile);
    try {
        long startWrite = System.currentTimeMillis();
        RDFWriter rdfWriter = rdfWriterFactory.getWriter(out);
        setupWriterConfig(rdfWriter.getWriterConfig());
        // Test prefixed URIs for only some of the URIs available
        rdfWriter.handleNamespace(RDF.PREFIX, RDF.NAMESPACE);
        rdfWriter.handleNamespace(SKOS.PREFIX, SKOS.NAMESPACE);
        rdfWriter.handleNamespace(FOAF.PREFIX, FOAF.NAMESPACE);
        rdfWriter.handleNamespace(EARL.PREFIX, EARL.NAMESPACE);
        rdfWriter.handleNamespace("ex", exNs);
        rdfWriter.startRDF();

        for (Statement nextSt : model) {
            rdfWriter.handleStatement(nextSt);
        }

        rdfWriter.endRDF();
        long endWrite = System.currentTimeMillis();
        System.out.println(
                "Write took: " + (endWrite - startWrite) + " ms (" + rdfWriterFactory.getRDFFormat() + ")");
        System.out.println("File size (bytes): " + testFile.length());
    } finally {
        out.close();
    }

    FileInputStream in = new FileInputStream(testFile);
    try {
        RDFParser rdfParser = rdfParserFactory.getParser();
        setupParserConfig(rdfParser.getParserConfig());
        rdfParser.setValueFactory(vf);
        Model parsedModel = new LinkedHashModel();
        if (storeParsedStatements) {
            rdfParser.setRDFHandler(new StatementCollector(parsedModel));
        }
        long startParse = System.currentTimeMillis();
        rdfParser.parse(in, "foo:bar");
        long endParse = System.currentTimeMillis();
        System.out.println(
                "Parse took: " + (endParse - startParse) + " ms (" + rdfParserFactory.getRDFFormat() + ")");

        if (storeParsedStatements) {
            if (model.size() != parsedModel.size()) {
                if (model.size() < 1000) {
                    boolean originalIsSubset = Models.isSubset(model, parsedModel);
                    boolean parsedIsSubset = Models.isSubset(parsedModel, model);
                    System.out.println("originalIsSubset=" + originalIsSubset);
                    System.out.println("parsedIsSubset=" + parsedIsSubset);

                    System.out.println("Written statements=>");
                    IOUtils.writeLines(IOUtils.readLines(new FileInputStream(testFile)), "\n", System.out);
                    System.out.println("Parsed statements=>");
                    Rio.write(parsedModel, System.out, RDFFormat.NQUADS);
                }
            }
            assertEquals("Unexpected number of statements, expected " + model.size() + " found "
                    + parsedModel.size(), model.size(), parsedModel.size());

            if (rdfParser.getRDFFormat().supportsNamespaces()) {
                assertTrue("Expected at least 5 namespaces, found " + parsedModel.getNamespaces().size(),
                        parsedModel.getNamespaces().size() >= 5);
                assertEquals(exNs, parsedModel.getNamespace("ex").get().getName());
            }
        }
    } finally {
        in.close();
    }
}

From source file:org.eclipse.smarthome.config.dispatch.test.ConfigDispatcherOSGiTest.java

private void truncateLastLine(File file) throws IOException {
    List<String> lines = IOUtils.readLines(new FileInputStream(file));
    IOUtils.writeLines(lines.subList(0, lines.size() - 1), "\n", new FileOutputStream(file));
}

From source file:org.esa.nest.util.FileIOUtils.java

/**
 * Reads a text file and replaces all outText with newText
 * @param inFile input file// w w w  . j  a  v  a  2  s  .  c  om
 * @param outFile output file
 * @param oldText text to replace
 * @param newText replacement text
 * @throws IOException on io error
 */
public static void replaceText(final File inFile, final File outFile, final String oldText,
        final String newText) throws IOException {
    final List<String> lines;
    try (FileReader fileReader = new FileReader(inFile)) {
        lines = IOUtils.readLines(fileReader);

        for (int i = 0; i < lines.size(); ++i) {
            String line = lines.get(i);
            if (line.contains(oldText)) {
                lines.set(i, line.replaceAll(oldText, newText));
            }
        }
    }

    if (!lines.isEmpty()) {
        try (FileWriter fileWriter = new FileWriter(outFile)) {
            IOUtils.writeLines(lines, "\n", fileWriter);
        }

    }
}

From source file:org.jahia.utils.maven.plugin.buildautomation.ConfigureMojo.java

private void adjustCatalinaProperties() throws IOException {
    // check if the catalina.properties have to be adjusted
    File catalinaProps = new File(targetServerDirectory, "conf/catalina.properties");
    String content = FileUtils.readFileToString(catalinaProps);
    if (!content.contains("${catalina.home}/digital-factory-config")) {
        List<String> lines = IOUtils.readLines(new StringReader(content));
        List<String> modifiedLines = new LinkedList<String>();
        for (String line : lines) {
            modifiedLines.add(line.startsWith("common.loader") ? addPathToCommonLoader(line) : line);
        }// w  w w.  java2 s  .  co m
        FileWriter fileWriter = new FileWriter(catalinaProps);
        try {
            IOUtils.writeLines(modifiedLines, null, fileWriter);
            fileWriter.flush();
            getLog().info("Adjusted common.loader value in the catalina.properties"
                    + " to reference digital-factory-config directory");
        } finally {
            IOUtils.closeQuietly(fileWriter);
        }
    }
}

From source file:org.jenkinsci.plugins.pipeline.modeldefinition.DeclarativeLinterCommand.java

protected int run() throws Exception {
    Jenkins.getInstance().checkPermission(READ);
    int retVal = 0;
    List<String> output = new ArrayList<>();

    String script = IOUtils.toString(stdin);

    if (script != null) {
        try {//from w  ww.  j  a v a 2  s  .  c o m
            Converter.scriptToPipelineDef(script);
            output.add("Jenkinsfile successfully validated.");
            retVal = 0;
        } catch (Exception e) {
            output.add("Errors encountered validating Jenkinsfile:");
            retVal = 1;
            output.addAll(ModelConverterAction.errorToStrings(e));
        }
    }

    IOUtils.writeLines(output, null, stdout);

    return retVal;
}

From source file:org.kuali.student.git.model.SvnRevisionMapper.java

private long createRevisionEntry(RandomAccessFile dataFile, long endOfDataFileOffset, long revision,
        List<String> revisionLines) throws IOException {

    OutputStream revisionMappingStream = null;

    ByteArrayOutputStream bytesOut;

    revisionMappingStream = new BZip2CompressorOutputStream(bytesOut = new ByteArrayOutputStream());

    PrintWriter pw = new PrintWriter(revisionMappingStream);

    IOUtils.writeLines(revisionLines, "\n", pw);

    pw.flush();//from   w  w  w  .  j  a  v a 2s.  co  m

    pw.close();

    byte[] data = bytesOut.toByteArray();

    dataFile.seek(endOfDataFileOffset);

    dataFile.write(data);

    return data.length;
}

From source file:org.openhab.binding.withings.internal.api.WithingsAccount.java

private Map<String, String> store(Map<String, String> config, File file) throws IOException {
    FileOutputStream os = new FileOutputStream(file);

    List<String> lines = new ArrayList<String>();
    for (Entry<String, String> line : config.entrySet()) {
        String value = isBlank(line.getValue()) ? "" : "=" + line.getValue();
        lines.add(line.getKey() + value);
    }/*  ww w.  j a  va2 s.c  o  m*/

    IOUtils.writeLines(lines, System.getProperty("line.separator"), os);
    IOUtils.closeQuietly(os);
    return config;
}

From source file:org.openhab.io.habmin.services.bundle.BindingConfigResource.java

private BindingBean putBinding(String uriPath, String bundle, BindingConfigListBean properties) {
    if (properties == null)
        return null;

    File configFile = new File("configurations/openhab.cfg");
    try {//  w w w  .j  a v  a 2 s.  co  m
        // Read all the lines in the config file
        List<String> linesIn = IOUtils.readLines(new FileInputStream(configFile));

        // Scan the config file to find the end of the relevant section
        int sectionEndLine = -1;
        for (int cnt = 0; cnt < linesIn.size(); cnt++) {
            String[] contents = parseLine(configFile.getPath(), linesIn.get(cnt), true);

            if (contents == null)
                continue;

            if (properties.pid.equals(contents[0]))
                sectionEndLine = cnt + 1;
        }

        // Loop through the config file looking for all the lines for this binding
        for (BindingConfigBean config : properties.entries) {
            boolean found = false;

            for (int cnt = 0; cnt < linesIn.size(); cnt++) {
                String[] contents = parseLine(configFile.getPath(), linesIn.get(cnt), true);
                // no valid configuration line, so continue
                if (contents == null)
                    continue;

                if (!properties.pid.equals(contents[0]))
                    continue;

                if (!config.name.equals(contents[1]))
                    continue;

                // Found a config setting
                if (config.value.isEmpty()) {
                    // If this is an interface setting (has a . in the parameter) then just delete it
                    if (contents[1].contains(".")) {
                        linesIn.remove(cnt);
                        if (sectionEndLine != -1)
                            sectionEndLine--;
                    } else
                        linesIn.set(cnt, "#" + contents[0] + ":" + contents[1] + " = " + contents[2]);
                } else
                    linesIn.set(cnt, contents[0] + ":" + contents[1] + " = " + config.value);

                found = true;
                break;
            }

            // Did we find the setting in the file?
            if (found == false && !config.value.isEmpty()) {
                // Nope!
                // Add it to the end of the section
                if (sectionEndLine == -1) {
                    linesIn.add("");
                    linesIn.add(properties.pid + ":" + config.name + " = " + config.value);
                } else {
                    linesIn.add(sectionEndLine++, "");
                    linesIn.add(sectionEndLine++, properties.pid + ":" + config.name + " = " + config.value);
                }
            }
        }

        // Everything is updated - just write the file to disk!
        BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8"));

        IOUtils.writeLines(linesIn, "\r\n", out);

        out.close();

    } catch (IOException e) {
        logger.debug("Error reading config file: " + e);
    }

    return getBinding(uriPath, bundle);
}