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:se.trixon.toolbox.photokml.PhotoKmlTopComponent.java

private void saveLogFile(File file) {
    try {/*from ww  w  . j a v a 2  s.  c o m*/
        FileUtils.writeLines(file, Arrays.asList(mLogBuilder.toString().split("\n")));
    } catch (IOException ex) {
        Message.error(Dict.IO_ERROR_TITLE.getString(),
                String.format(Dict.FILE_ERROR_WRITE_MESSAGE.getString(), file.getAbsolutePath()));
    }
}

From source file:simplealbum.mvc.picture.impl.SenderFTP.java

public void stop() throws IOException {
    FileUtils.writeLines(new File(logPath), listLog);
}

From source file:spade.reporter.Audit.java

/**
 * Creates a temp file in the given tempDir from the list of audit log files
 * //from  ww w.j  a  va2  s. c om
 * Returns the path of the temp file is that is created successfully
 * Else returns null
 * 
 * @param spadeAuditBridgeBinaryName name of the spade audit bridge binary
 * @param inputLogFiles list of audit log files (in the defined order)
 * @param tempDirPath path of the temp dir
 * @return path of the temp file which contains the paths of audit logs OR null
 */
private String createLogListFileForSpadeAuditBridge(String spadeAuditBridgeBinaryName,
        List<String> inputLogFiles, String tempDirPath) {
    try {
        String spadeAuditBridgeInputFilePath = tempDirPath + File.separatorChar + spadeAuditBridgeBinaryName
                + "." + System.nanoTime();
        File spadeAuditBridgeInputFile = new File(spadeAuditBridgeInputFilePath);
        if (!spadeAuditBridgeInputFile.createNewFile()) {
            logger.log(Level.SEVERE, "Failed to create input file list file for " + spadeAuditBridgeBinaryName);
            return null;
        } else {
            FileUtils.writeLines(spadeAuditBridgeInputFile, inputLogFiles);
            return spadeAuditBridgeInputFile.getAbsolutePath();
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Failed to create input file for " + spadeAuditBridgeBinaryName, e);
    }
    return null;
}

From source file:spade.utility.FileUtility.java

/**
 * Path must be valid, exist, be a file, and be writable.
 */// w  w w  .j a v a2  s .com
public static void writeLines(String path, List<String> lines) throws Exception {
    if (doesPathExist(path)) {
        if (!isFileWritable(path)) {
            throw new Exception("File is not writable");
        }
    } else {
        if (!createFile(path)) {
            throw new Exception("Failed to create file");
        }
    }
    FileUtils.writeLines(getFile(path), lines);
}

From source file:specminers.evaluation.ForbiddenSequencesExtractor.java

private static void extractInvalidSequences(Map<String, String> options) throws IOException, ParseException {
    File mopFilesFolder = new File(options.get(INPUT_PATH_OPTION));
    String[] extensions = new String[] { MopExtractor.MOP_FILES_EXTENSION };
    List<File> files = FileUtils.listFiles(mopFilesFolder, extensions, true).stream()
            .collect(Collectors.toList());

    List<String> forbiddenSequences = new LinkedList<>();

    for (File f : files) {
        MopExtractor extractor = new MopExtractor(f);

        if (extractor.containsParseableSpec()) {
            List<String> newLines = extractor.getForbiddenSequences();
            newLines = newLines.stream()//.map(l -> l + "\t\t--File: " + f.getAbsolutePath())
                    .collect(Collectors.toList());
            forbiddenSequences.addAll(newLines);

        }/*ww w  .  ja v a  2 s .c o  m*/
    }

    File outputDir = new File(options.get(OUTPUT_OPTION));

    if (outputDir == null || !outputDir.exists()) {
        forbiddenSequences.forEach(l -> System.out.println(l));
    } else {
        File forbiddenSeqsFile;
        forbiddenSeqsFile = java.nio.file.Paths.get(outputDir.getAbsolutePath(), "forbidden_sequences.txt")
                .toFile();
        FileUtils.writeLines(forbiddenSeqsFile, forbiddenSequences);

    }
}

From source file:specminers.evaluation.GetMethods.java

private static void extractRegexFromJavaFiles(Map<String, String> options) throws IOException {
    File javaFilesFolder = new File(options.get(PATH_OPTION));
    String[] extensions = new String[] { "java" };
    File outputDir = null;/*from   ww  w . j  a v a 2s  .  c  o  m*/

    if (options.containsKey(OUTPUT_OPTION)) {
        outputDir = new File(options.get(OUTPUT_OPTION));
    }

    List<File> sourceFiles = FileUtils.listFiles(javaFilesFolder, extensions, true).stream()
            .collect(Collectors.toList());

    for (File sourceFile : sourceFiles) {
        GetMethodsViaRegexExtractor extractor = new GetMethodsViaRegexExtractor(sourceFile);

        // Set<String> result = new HashSet<>(extractor.getReadOnlyMethods());
        Set<String> result = new HashSet<>(extractor.getAllMethods());

        if (outputDir != null && outputDir.exists()) {
            File regexesFile;
            regexesFile = java.nio.file.Paths.get(outputDir.getAbsolutePath(),
                    sourceFile.getName().replace(".java", "") + "_read_operations.txt").toFile();
            FileUtils.writeLines(regexesFile, result);

        } else {
            System.out.println("Read operations found on file " + sourceFile.getName());
            result.forEach(l -> System.out.println(l));
        }
    }
}

From source file:specminers.evaluation.JflapStatsCollector.java

private static void extendedOriginalSpecification(Map<String, String> options)
        throws IOException, ParseException {

    File originalSpecsFolder = new File(options.get(JFLAP_PATH_OPTION));
    String[] extensions = new String[] { "jff" };
    File outputDir = null;/*from   www . java 2s.  c  om*/

    if (options.containsKey(OUTPUT_OPTION)) {
        outputDir = new File(options.get(OUTPUT_OPTION));
    }

    List<File> originalSpecFiles = FileUtils.listFiles(originalSpecsFolder, extensions, true).stream()
            .collect(Collectors.toList());

    List<String> lines = new LinkedList<>();
    for (File file : originalSpecFiles) {
        JflapFileManipulator jffManipulator = new JflapFileManipulator(file);
        AutomataStats stats = jffManipulator.getAutomataStats();
        String line = FilenameUtils.removeExtension(file.getName()) + ";" + stats.getShortestScenario() + ";"
                + stats.getShortestScenarioExample() + ";" + stats.getLongestScenario() + ";"
                + stats.getLongestScenarioExample() + ";" + stats.getNumberOfScenarios();
        lines.add(line);
    }

    String statsPath = Paths.get(outputDir.getPath(), StringHelper.getCurrentDateTimeStamp() + "_"
            + originalSpecsFolder.getName() + "automata_statistics.txt").toFile().getAbsolutePath();
    FileUtils.writeLines(new File(statsPath), lines);
}

From source file:specminers.evaluation.PradelRefSpecsExtender.java

private static void extendedOriginalSpecification(Map<String, String> options) throws IOException {
    Map<String, Set<String>> publicAPI = getClassesPublicMethods(options.get(SOURCE_CODE_PATH_OPTION));

    File originalSpecsFolder = new File(options.get(JFLAP_PATH_OPTION));
    String[] extensions = new String[] { "jff" };
    File outputDir = null;//from   w  ww. ja v a  2  s.c  om

    if (options.containsKey(OUTPUT_OPTION)) {
        outputDir = new File(options.get(OUTPUT_OPTION));
    }

    if (options.containsKey(PUBLIC_API_OUTPUT_FOLDER)) {
        File apiFolder = new File(options.get(PUBLIC_API_OUTPUT_FOLDER));

        if (apiFolder.exists()) {
            publicAPI.keySet().stream().forEach(k -> {
                File clazzAPI = new File(apiFolder, k + "_public_methods.txt");
                try {
                    FileUtils.writeLines(clazzAPI, publicAPI.get(k));
                } catch (IOException ex) {
                    Logger.getLogger(PradelRefSpecsExtender.class.getName()).log(Level.SEVERE, null, ex);
                }
            });
        }
    } else {

        List<File> originalSpecFiles = FileUtils.listFiles(originalSpecsFolder, extensions, true).stream()
                .collect(Collectors.toList());

        for (File file : originalSpecFiles) {
            JflapFileManipulator jffManipulator = new JflapFileManipulator(file);
            jffManipulator.includeTransitions(publicAPI, false);
            String extendedSpecPath = Paths
                    .get(outputDir.getPath(), file.getName().replace(".jff", "_package_extended.jff")).toFile()
                    .getAbsolutePath();
            jffManipulator.saveToFile(extendedSpecPath);
        }
    }
}

From source file:specminers.evaluation.PrecisionEvaluator.java

private static void collectPrecisionStatisticsPerClass(Map<String, String> options)
        throws IOException, ParseException {

    File testFilesFolder = new File(options.get(JFLAP_FULL_REFERENCE_SPECS_PATH));
    File originalReferenceSpecFolder = new File(options.get(JFLAP_ORIGINAL_REFERENCE_SPECS_PATH));
    String[] extensions = new String[] { "jff" };
    String[] traceFileExtension = new String[] { "txt" };

    List<File> files = FileUtils.listFiles(testFilesFolder, extensions, true).stream()
            .collect(Collectors.toList());

    List<File> originalSpecFiles = FileUtils.listFiles(originalReferenceSpecFolder, extensions, true).stream()
            .collect(Collectors.toList());

    // Key: class name Value: list of trace files containing filtered
    // unit test traces.
    Map<String, TracePrecisionStatistics> testTraces = new HashMap<>();

    Map<File, Set<String>> acceptedInternalTraces = new HashMap<>();
    Map<File, Set<String>> rejectedInternalTraces = new HashMap<>();
    Map<File, Set<String>> acceptedExternalTraces = new HashMap<>();
    Map<File, Set<String>> rejectedExternalTraces = new HashMap<>();

    Set<File> filesWithTraces = new HashSet<>();
    for (File f : files) {

        String testedClass = f.getName()
                .replace("_jflap_automaton_package_extended_package_full_merged_spec.jff", "");
        String testedClassSimpleName = testedClass.substring(testedClass.lastIndexOf(".") + 1);
        File tracesFolder = Paths.get(options.get(TRACES_PATH_OPTION), testedClassSimpleName).toFile();
        if (!tracesFolder.isDirectory() || !tracesFolder.exists()) {
            continue;
        }/*from   w w  w.  j a v  a2s.c  o  m*/

        Collection<File> traces = FileUtils.listFiles(tracesFolder, traceFileExtension, true);

        if (traces.isEmpty()) {
            continue;
        }

        filesWithTraces.add(f);

        TracePrecisionStatistics statistics = new TracePrecisionStatistics();
        statistics.className = testedClass;
        statistics.numberOfExternalTraces = 0;
        statistics.numberOfAcceptedExternalTraces = 0;
        statistics.numberOfInternalTraces = 0;
        statistics.numberOfAcceptedInternalTraces = 0;

        JflapFileManipulator jff = new JflapFileManipulator(f);
        Set<List<String>> minedSeqs;
        minedSeqs = new HashSet<>();

        acceptedInternalTraces.put(f, new HashSet<>());
        rejectedInternalTraces.put(f, new HashSet<>());
        acceptedExternalTraces.put(f, new HashSet<>());
        rejectedExternalTraces.put(f, new HashSet<>());

        for (File t : traces) {
            String fullTrace = FileUtils.readFileToString(t).trim();
            //boolean isExternalTest = !fullTrace.contains("xception");
            boolean isExternalTest = t.getAbsolutePath().contains("external");

            List<String> traceCalls = Stream.of(fullTrace.split("\\)"))
                    .map(call -> call.replace(".init<>", ".<init>") + ")").collect(Collectors.toList());

            minedSeqs.add(traceCalls);

            if (isExternalTest) {
                statistics.numberOfExternalTraces++;
                if (jff.acceptsSequence(traceCalls)) {
                    statistics.numberOfAcceptedExternalTraces++;
                    acceptedExternalTraces.get(f).add(t.getName() + ": " + fullTrace);
                } else {
                    rejectedExternalTraces.get(f).add(t.getName() + ": " + fullTrace);
                }
            } else {
                statistics.numberOfInternalTraces++;
                // Tests for protection via exceptions being thrown
                // should not lead to an accepting state!
                if (!jff.acceptsSequence(traceCalls)) {
                    statistics.numberOfAcceptedInternalTraces++;
                    acceptedInternalTraces.get(f).add(t.getName() + ": " + fullTrace);
                } else {
                    rejectedInternalTraces.get(f).add(t.getName() + ": " + fullTrace);
                }
            }
        }

        File originalReferenceSpec = originalSpecFiles.stream()
                .filter(refFile -> refFile.getName().equals(testedClass + "_jflap_automaton.jff")).findFirst()
                .get();

        testTraces.put(testedClass, statistics);
    }

    List<String> allStats = new LinkedList<>();
    String header = "Class;External Traces;Accepted External Traces;External Precision;Internal Traces;Accepted Internal Traces;Internal Precision";
    for (String clazz : testTraces.keySet()) {
        File statsFile = Paths.get(options.get(OUTPUT_OPTION), clazz + "_statistics.txt").toFile();
        TracePrecisionStatistics st = testTraces.get(clazz);
        double externalPrecision = st.numberOfAcceptedExternalTraces * 1D / st.numberOfExternalTraces;
        double internalPrecision = st.numberOfAcceptedInternalTraces * 1D / st.numberOfInternalTraces;
        String stats = String.format("%s;%s;%s;%f;%s;%s;%f", st.className, st.numberOfExternalTraces,
                st.numberOfAcceptedExternalTraces, externalPrecision, st.numberOfInternalTraces,
                st.numberOfAcceptedInternalTraces, internalPrecision);

        List<String> lines = new LinkedList();
        lines.add(header);
        lines.add(stats);
        FileUtils.writeLines(statsFile, lines);

        if (st.numberOfExternalTraces > 0 || st.numberOfInternalTraces > 0) {
            allStats.add(stats);
        }

    }

    allStats.add(0, header);
    File allStatsFile = Paths.get(options.get(OUTPUT_OPTION), "full_statistics.txt").toFile();

    FileUtils.writeLines(allStatsFile, allStats);

    List<String> allDetailsLines = new LinkedList<>();

    for (File f : filesWithTraces) {

        String testedClass = f.getName()
                .replace("_jflap_automaton_package_extended_package_full_merged_spec.jff", "");
        File detailsFile = Paths.get(options.get(OUTPUT_OPTION), testedClass + "_details.txt").toFile();
        List<String> lines = new LinkedList<>();
        lines.add(IntStream.range(0, 150).boxed().map(i -> "*").collect(Collectors.joining()));
        lines.add(String.format("Details for class: %s", testedClass));
        lines.add(IntStream.range(0, 150).boxed().map(i -> "*").collect(Collectors.joining()));
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        lines.add("Accepted external traces");
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        acceptedExternalTraces.get(f).forEach(seq -> lines.add(seq));
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        lines.add("Rejected external traces");
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        rejectedExternalTraces.get(f).forEach(seq -> lines.add(seq));
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        lines.add("Accepted internal traces");
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        acceptedInternalTraces.get(f).forEach(seq -> lines.add(seq));
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        lines.add("Rejected internal traces");
        lines.add(IntStream.range(0, 30).boxed().map(i -> "=").collect(Collectors.joining()));
        rejectedInternalTraces.get(f).forEach(seq -> lines.add(seq));
        lines.add("");
        FileUtils.writeLines(detailsFile, lines);
        allDetailsLines.addAll(lines);
    }

    File allDetailsFile = Paths.get(options.get(OUTPUT_OPTION), "full_details.txt").toFile();
    FileUtils.writeLines(allDetailsFile, allDetailsLines);

}

From source file:specminers.evaluation.RandoopAnalyzer.java

private static void extendedOriginalSpecification(Map<String, String> options)
        throws IOException, ParseException {

    File testsFolder = new File(options.get(RANDOOP_TESTS_FOLDER));
    String[] extensions = new String[] { "java" };
    File outputDir = null;//  ww  w.  j  av  a 2 s .c  o  m

    if (options.containsKey(OUTPUT_OPTION)) {
        outputDir = new File(options.get(OUTPUT_OPTION));
    } else {
        outputDir = FileUtils.getTempDirectory();
        System.out.println("Files will be generated at folder " + outputDir.getAbsolutePath());
    }

    for (File classFolder : testsFolder.listFiles()) {
        if (classFolder.isDirectory()) {
            List<File> timeIntervalFolders;
            timeIntervalFolders = Arrays
                    .asList(classFolder.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY));

            List<String> classDetails = new LinkedList<>();
            Set<String> classSequences = new HashSet<>();

            for (File containingFolder : timeIntervalFolders) {
                List<String> lines = new LinkedList<>();
                Set<String> sequenceLines = new HashSet<>();
                List<File> genTests = FileUtils.listFiles(containingFolder, extensions, true).stream()
                        .collect(Collectors.toList());

                for (File file : genTests) {
                    if (file.getName().equals("RandoopTest.java")) {
                        continue;
                    }
                    RandoopGeneratedTestParser ra = new RandoopGeneratedTestParser(file);

                    for (String test : ra.getTestMethodDetails().keySet()) {

                        String details = "";

                        for (String det : ra.getTestMethodDetails().get(test).keySet()) {
                            details += det + ";" + ra.getTestMethodDetails().get(test).get(det);
                        }

                        String line = test + ";" + details;
                        lines.add(line);

                        String sequence = ra.getTestMethodDetails().get(test).get("statementsBeforeTryCatch");
                        if (!StringUtils.isEmpty(sequence)) {
                            sequenceLines.add(sequence.trim());
                        }
                    }
                }

                String statsPath = Paths.get(outputDir.getPath(),
                        classFolder.getName() + "_" + containingFolder.getName() + "_test_statistics.txt")
                        .toFile().getAbsolutePath();
                String sequencesPath = Paths
                        .get(outputDir.getPath(),
                                classFolder.getName() + "_" + containingFolder.getName() + "_sequences.txt")
                        .toFile().getAbsolutePath();
                FileUtils.writeLines(new File(statsPath), lines);
                FileUtils.writeLines(new File(sequencesPath), sequenceLines);

                classDetails.addAll(lines);
                classSequences.addAll(sequenceLines);
            }

            String classStatsPath = Paths
                    .get(outputDir.getPath(), classFolder.getName() + "_" + "all_tests_statistics.txt").toFile()
                    .getAbsolutePath();
            String classSequencesPath = Paths
                    .get(outputDir.getPath(), classFolder.getName() + "_all_sequences.txt").toFile()
                    .getAbsolutePath();

            FileUtils.writeLines(new File(classStatsPath), classDetails);
            FileUtils.writeLines(new File(classSequencesPath), classSequences);

        }
    }
    List<File> originalSpecFiles = FileUtils.listFiles(testsFolder, extensions, true).stream()
            .collect(Collectors.toList());

    List<String> lines = new LinkedList<>();
    lines.add("Test File;Test Number;Valid Statements;Handles Exception?");
    for (File file : originalSpecFiles) {
        if (file.getName().equals("RandoopTest.java")) {
            continue;
        }
        RandoopGeneratedTestParser ra = new RandoopGeneratedTestParser(file);

        for (String test : ra.getTestMethodDetails().keySet()) {

            String details = ra.getTestMethodDetails().get(test).keySet().stream()
                    .map(det -> ra.getTestMethodDetails().get(test).get(det)).collect(Collectors.joining(";"));

            String line = file.getName() + ";" + test + ";" + details;
            lines.add(line);
        }
    }

    String statsPath = Paths.get(outputDir.getPath(), "test_details.txt").toFile().getAbsolutePath();
    FileUtils.writeLines(new File(statsPath), lines);
}