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:com.doculibre.constellio.utils.license.ApplyLicenseUtils.java

/**
 * @param args/*w w  w . ja v  a2 s  .  c om*/
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    URL licenceHeaderURL = ApplyLicenseUtils.class.getResource("LICENSE_HEADER");
    File binDir = ClasspathUtils.getClassesDir();
    File projectDir = binDir.getParentFile();
    //        File dryrunDir = new File(projectDir, "dryrun");
    File licenceFile = new File(licenceHeaderURL.toURI());
    List<String> licenceLines = readLines(licenceFile);
    //        for (int i = 0; i < licenceLines.size(); i++) {
    //            String licenceLine = licenceLines.get(i);
    //            licenceLines.set(i, " * " + licenceLine);
    //        }
    //        licenceLines.add(0, "/**");
    //        licenceLines.add(" */");

    List<File> javaFiles = (List<File>) org.apache.commons.io.FileUtils.listFiles(projectDir,
            new String[] { "java" }, true);
    for (File javaFile : javaFiles) {
        if (isValidPackage(javaFile)) {
            List<String> javaFileLines = readLines(javaFile);
            if (!javaFileLines.isEmpty()) {
                boolean modified = false;
                String firstLineTrim = javaFileLines.get(0).trim();
                if (firstLineTrim.startsWith("package")) {
                    modified = true;
                    javaFileLines.addAll(0, licenceLines);
                } else if (firstLineTrim.startsWith("/**")) {
                    int indexOfEndCommentLine = -1;
                    loop2: for (int i = 0; i < javaFileLines.size(); i++) {
                        String javaFileLine = javaFileLines.get(i);
                        if (javaFileLine.indexOf("*/") != -1) {
                            indexOfEndCommentLine = i;
                            break loop2;
                        }
                    }
                    if (indexOfEndCommentLine != -1) {
                        modified = true;
                        int i = 0;
                        loop3: for (Iterator<String> it = javaFileLines.iterator(); it.hasNext();) {
                            it.next();
                            if (i <= indexOfEndCommentLine) {
                                it.remove();
                            } else {
                                break loop3;
                            }
                            i++;
                        }
                        javaFileLines.addAll(0, licenceLines);
                    } else {
                        throw new RuntimeException(
                                "Missing end comment for file " + javaFile.getAbsolutePath());
                    }
                }

                if (modified) {
                    //                        String outputFilePath = javaFile.getPath().substring(projectDir.getPath().length());
                    //                        File outputFile = new File(dryrunDir, outputFilePath);
                    //                        outputFile.getParentFile().mkdirs();
                    //                        System.out.println(outputFile.getPath());
                    //                        FileOutputStream fos = new FileOutputStream(outputFile);
                    System.out.println(javaFile.getPath());
                    FileOutputStream fos = new FileOutputStream(javaFile);
                    IOUtils.writeLines(javaFileLines, "\n", fos);
                    IOUtils.closeQuietly(fos);
                }
            }
        }
    }
}

From source file:com.alexholmes.hadooputils.io.FileUtils.java

/**
 * Writes the array list into a file as newline-separated lines.
 *
 * @param fs a Hadoop file system//from  ww w.j  a va  2  s  .c  o m
 * @param p  the file path
 * @return array of lines to write to the file
 * @throws java.io.IOException if something goes wrong
 */
public static void writeLines(Collection<?> lines, final FileSystem fs, final Path p) throws IOException {
    OutputStream stream = fs.create(p);
    try {
        IOUtils.writeLines(lines, IOUtils.LINE_SEPARATOR, stream);
    } finally {
        stream.close();
    }
}

From source file:au.org.ala.delta.util.LocalConfigFiles.java

private File getFile(String filename, String resourcePath) {
    File f = new File(
            String.format("%s%s%s", getSettingsDirectory().getAbsolutePath(), File.separator, filename));
    if (!f.exists()) {
        InputStream is = LocalConfigFiles.class.getResourceAsStream(resourcePath);
        if (is != null) {
            try {
                List<String> lines = IOUtils.readLines(is);
                FileWriter writer = new FileWriter(f);
                IOUtils.writeLines(lines, LINE_ENDING, writer);
                writer.flush();//from   w  w  w.ja  va 2s. co  m
                writer.close();
            } catch (IOException ioex) {
                throw new RuntimeException(ioex);
            }
        }
    }

    return f;
}

From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java

private Path createFile(List<String> lines) throws IOException {
    Path file = new File(testDir, UUID.randomUUID().toString()).toPath();
    try (Writer writer = new FileWriter(file.toFile())) {
        IOUtils.writeLines(lines, "", writer);
    }/* w  w w  .ja  va 2s  .c  om*/
    return file;
}

From source file:de.andrena.tools.macker.plugin.CommandLineFileTest.java

private void writeArgsFile(List<String> lines) throws IOException {
    Writer out = new OutputStreamWriter(new FileOutputStream(TEST_FILE), "UTF-8");
    IOUtils.writeLines(lines, "\n", out);
    out.flush();/* w ww. j a  va2s .  com*/
    out.close();
}

From source file:com.adguard.android.db.FilterRuleDaoImpl.java

@Override
public void setFilterRules(int filterId, List<String> rules) {
    try {/*from  w ww.  jav  a  2 s . com*/
        String fileName = getOrCreateFilterFile(filterId);
        context.deleteFile(fileName);
        OutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        IOUtils.writeLines(rules, null, outputStream);
    } catch (Exception ex) {
        log.error("Cannot insert new rules to filter {}:\r\n{}", filterId, ex);
        throw new RuntimeException("Cannot insert new rules to filter " + filterId, ex);
    }
}

From source file:gov.nih.nci.nbia.servlet.DownloadServletVersion.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String os = request.getParameter(osParam);
    String urlForDownload = null;
    if (os.startsWith("windows")) {
        urlForDownload = winUrl;/*from   w w  w  .j  ava 2 s. c  om*/
    } else if (os.startsWith("mac")) {
        urlForDownload = macUrl;
    } else if (os.equals("CentOS")) {
        urlForDownload = centOsUrl;
    } else if (os.equals("Ubuntu")) {
        urlForDownload = ubuntuUrl;
    }

    String forcedGrade = null;
    try {
        forcedGrade = NCIAConfig.getDownloaderAppForcedUpgrade();
    } catch (RuntimeException ex) {
        forcedGrade = "false";
        //ex.printStackTrace();
    }

    response.setStatus(HttpServletResponse.SC_OK);

    List<String> readLines = new ArrayList<String>();
    readLines.add(NCIAConfig.getLatestDownloaderVersion());
    readLines.add(urlForDownload);
    readLines.add(NCIAConfig.getEncryptionKey());
    readLines.add(forcedGrade);
    readLines.add(helpDeskLink);
    readLines.add(wikiLink);
    OutputStream outStream = response.getOutputStream();
    IOUtils.writeLines(readLines, System.getProperty("line.separator"), outStream);
    outStream.close();
}

From source file:com.jgui.ttscrape.IgnoreListFilter.java

/**
 * Sort then write the file to disk.//from  w  w  w  .  j  a  v  a  2  s.  co  m
 */
private void writeIgnoreFile() {
    try {
        Collections.sort(titlesToIgnore);
        FileWriter writer = new FileWriter(ignoreFile);
        IOUtils.writeLines(fileHeader, null, writer);
        IOUtils.writeLines(titlesToIgnore, null, writer);
        writer.close();
    } catch (Exception ex) {
        logger.error("failed to write ignore file", ex);
    }
}

From source file:ee.ria.xroad.common.conf.globalconf.DownloadedFiles.java

void save() throws Exception {
    log.trace("save()");

    try (FileWriter file = new FileWriter(confFile.toFile())) {
        IOUtils.writeLines(oldList, null, file);
    }/*from w  w w. j a va  2 s . c o  m*/
}

From source file:gov.nih.nci.nbia.basket.DynamicJNLPGenerator.java

public String generate(String userId, String password, String codebase, String downloadServerUrl,
        Boolean includeAnnotation, List<BasketSeriesItemBean> seriesItems, long currentTimeMillis,
        String noOfRetry) {/*from   w w w. j a  v  a2 s .c om*/
    this.codebase = codebase;
    String jnlp = "";
    try {
        StringBuffer jnlpBuilder = this.getJnlp();
        int size = seriesItems.size();
        StringBuffer argsBuilder = new StringBuffer();
        List<String> seriesDownloadData = new ArrayList<String>();
        for (int i = 0; i < size; i++) {
            BasketSeriesItemBean seriesItem = seriesItems.get(i);

            String collection = seriesItem.getProject();
            String patientId = seriesItem.getPatientId();
            String studyInstanceUid = seriesItem.getStudyId();
            String seriesInstanceUid = seriesItem.getSeriesId();
            String annotation = seriesItem.getAnnotated();
            Integer numberImages = seriesItem.getTotalImagesInSeries();
            Long imagesSize = seriesItem.getTotalSizeForAllImagesInSeries();
            Long annoSize = seriesItem.getAnnotationsSize();
            String url = "url";
            String displayName = "displayName";
            String studyDate = seriesItem.getStudyDate();
            String studyDesc = cleanStr(seriesItem.getStudyDescription());
            String seriesDesc = cleanStr(seriesItem.getSeriesDescription());
            String study_id = cleanStr(seriesItem.getStudy_id());
            String seriesNumber = seriesItem.getSeriesNumber();

            String argument = "" + collection + "|" + patientId + "|" + studyInstanceUid + "|"
                    + seriesInstanceUid + "|" + annotation + "|" + numberImages + "|" + imagesSize + "|"
                    + annoSize + "|" + url + "|" + displayName + "|" + true + "|" + studyDate + "|" + study_id
                    + "|" + studyDesc + "|" + seriesNumber + "|" + seriesDesc;
            seriesDownloadData.add(argument);
        }
        File dataFile = new File(System.getProperty("java.io.tmpdir"),
                "jnlp-data" + currentTimeMillis + ".txt");
        OutputStream os = new FileOutputStream(dataFile);
        IOUtils.writeLines(seriesDownloadData, System.getProperty("line.separator"), os);
        os.close();
        argsBuilder.append("<argument>").append(dataFile.getAbsolutePath()).append("</argument>");
        //get user id and included annotation
        StringBuffer propXMLBuilder = new StringBuffer();
        propXMLBuilder.append(this.getPropertyXML("jnlp.includeAnnotation", includeAnnotation.toString()));
        propXMLBuilder.append(this.getPropertyXML("jnlp.userId", userId));
        //this should be over secure connection
        String encryptedPassword = this.encrypt(userId, password);
        propXMLBuilder.append(this.getPropertyXML("jnlp.password", encryptedPassword));
        propXMLBuilder.append(this.getPropertyXML("jnlp.codebase", this.codebase));
        propXMLBuilder.append(this.getPropertyXML("jnlp.downloadServerUrl", downloadServerUrl));
        propXMLBuilder.append(this.getPropertyXML("jnlp.noofretry", noOfRetry));
        this.replaceProperties(propXMLBuilder, jnlpBuilder);
        this.replaceArguments(argsBuilder.toString(), jnlpBuilder);

        jnlp = jnlpBuilder.toString();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    return jnlp;
}