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:com.taobao.android.builder.tasks.app.LogDependenciesTask.java

@TaskAction
void generate() {

    AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(getVariantName());

    if (null == atlasDependencyTree) {
        return;/*from   w  w w .j  a  va  2 s  .  c  o m*/
    }

    File treeFile = new File(getProject().getBuildDir(),
            "outputs/dependencyTree-" + getVariantName() + ".json");
    File dependenciesFile = new File(getProject().getBuildDir(), "outputs/dependencies.txt");
    File versionProperties = new File(getProject().getBuildDir(), "outputs/version.properties");
    File buildInfo = new File(getProject().getBuildDir(), "outputs/build.txt");

    File atlasConfig = new File(getProject().getBuildDir(), "outputs/atlasConfig.json");

    appBuildInfo.setDependencyTreeFile(treeFile);
    appBuildInfo.setDependenciesFile(dependenciesFile);
    appBuildInfo.setVersionPropertiesFile(versionProperties);
    appBuildInfo.setBuildInfoFile(buildInfo);

    treeFile.delete();
    dependenciesFile.delete();
    versionProperties.delete();
    buildInfo.delete();

    treeFile.getParentFile().mkdirs();
    try {

        DependencyJson dependencyJson = atlasDependencyTree.getDependencyJson();

        Collections.sort(dependencyJson.getMainDex());

        FileUtils.write(treeFile, JSON.toJSONString(dependencyJson, true));

        //add to ap
        appBuildInfo.getOtherFilesMap().put("awo/dependencyTree.json", treeFile);

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        FileUtils.writeStringToFile(dependenciesFile,
                JSON.toJSONString(atlasDependencyTree.getDependencyJson()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        FileUtils.writeLines(versionProperties, getSortVersionList(atlasDependencyTree));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("gradleVersion:").append(getProject().getGradle().getGradleVersion()).append("\r\n");
    stringBuilder.append("mtlVersion:").append(Version.ANDROID_GRADLE_PLUGIN_VERSION).append("\r\n");
    stringBuilder.append("androidVersion:").append(PathUtil.getJarFile(AndroidBuilder.class)).append("\r\n");
    try {
        FileUtils.writeStringToFile(buildInfo, stringBuilder.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        FileUtils.write(atlasConfig,
                JSON.toJSONString(new AtlasExtensionOutput(appVariantContext.getAtlasExtension(),
                        appVariantContext.getBuildType().getName()), true));
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (null != AtlasBuildContext.conflictDependencies && !AtlasBuildContext.conflictDependencies.isEmpty()) {
        try {
            FileUtils.writeLines(
                    new File(getProject().getBuildDir(), "outputs/warning-dependencyConflict.properties"),
                    AtlasBuildContext.conflictDependencies);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (appVariantContext.getAtlasExtension().getTBuildConfig().isAbortIfDependencyConflict()) {
            throw new GradleException("???warning-dependencyConflict.properties");
        }
    }
}

From source file:com.taobao.android.builder.tools.proguard.AwbProguardConfiguration.java

/**
 * Print the proguard config file to the specified file
 *
 * @param outConfigFile// ww  w . j  ava 2 s . c  o m
 */
public List<File> printConfigFile(File outConfigFile) throws IOException {
    List<String> configs = Lists.newArrayList();
    List<File> bundleFiles = Lists.newArrayList();

    //awbProguard for no lib, convenient for predex
    for (AwbTransform awbTransform : awbTransforms) {

        List<File> inputLibraries = Lists.newArrayList();

        String name = awbTransform.getAwbBundle().getName();
        File obuscateDir = new File(awbObfuscatedDir, awbTransform.getAwbBundle().getName());
        obuscateDir.mkdirs();

        //configs.add();
        if (null != awbTransform.getInputDir() && awbTransform.getInputDir().exists()) {
            configs.add(INJARS_OPTION + " " + awbTransform.getInputDir().getAbsolutePath());
            bundleFiles.add(awbTransform.getInputDir());
            File obsJar = new File(obuscateDir, "inputdir_" + OBUSCATED_JAR);
            inputLibraries.add(obsJar);
            configs.add(OUTJARS_OPTION + " " + obsJar.getAbsolutePath());
        }

        Set<String> classNames = new HashSet<>();
        for (File inputLibrary : awbTransform.getInputLibraries()) {
            configs.add(INJARS_OPTION + " " + inputLibrary.getAbsolutePath());
            bundleFiles.add(inputLibrary);
            String fileName = inputLibrary.getName();

            if (classNames.contains(fileName)) {
                fileName = "a" + classNames.size() + "_" + fileName;
            }

            classNames.add(fileName);

            File obsJar = new File(obuscateDir, fileName);

            inputLibraries.add(obsJar);
            configs.add(OUTJARS_OPTION + " " + obsJar.getAbsolutePath());
        }
        //            configs.add();

        awbTransform.setInputFiles(inputLibraries);
        awbTransform.setInputDir(null);
        awbTransform.getInputLibraries().clear();
        appVariantOutputContext.getAwbTransformMap().put(name, awbTransform);
    }
    FileUtils.writeLines(outConfigFile, configs);
    return bundleFiles;
}

From source file:de.unisb.cs.st.javalanche.mutation.analyze.MutationScoreAnalyzer.java

/**
 * The analyze method that is called by the analyzeResults task. This method
 * calculates the mutation scores as well as additional test/type information
 * and outputs it to the display and a CSV file.
 *
 * @param mutations iterable set of mutations from system under test
 * @param report the HTML report that is being produced (untouched)
 * @return the class/method mutation score data in a string format
 *//*from ww w.j a v  a2  s .  c  o m*/
public String analyze(Iterable<Mutation> mutations, HtmlReport report) {

    // Acquire the CSV list of mutation types (KILLED and TOTAL)
    String mutationTypeString = "";
    for (Mutation.MutationType mutationType : Mutation.MutationType.values()) {
        mutationTypeString += "KILLED_" + mutationType.toString() + ",";
        mutationTypeString += "TOTAL_" + mutationType.toString() + ",";
    }

    collectClassMethodData(mutations);

    // Build up output for class and method data
    StringBuilder sb = new StringBuilder();
    sb.append(formatTitle("----------Class Mutation Score----------"));
    sb.append(formatHeading("Class Name:", "Of Covered", "Of Generated"));
    classScores.add("CLASS_NAME,KILLED_MUTANTS,COVERED_MUTANTS,GENERATED_MUTANTS,"
            + "MUTATION_SCORE_OF_COVERED_MUTANTS,MUTATION_SCORE_OF_GENERATED_MUTANTS," + mutationTypeString
            + "TESTS_TOUCHED");
    addClassData(sb);

    sb.append(formatTitle("----------Method Mutation Score----------"));
    sb.append(formatHeading("Method Name:", "Of Covered", "Of Generated"));
    methodScores.add("CLASS_NAME,METHOD_NAME,KILLED_MUTANTS,COVERED_MUTANTS,GENERATED_MUTANTS,"
            + "MUTATION_SCORE_OF_COVERED_MUTANTS,MUTATION_SCORE_OF_GENERATED_MUTANTS," + mutationTypeString
            + "TESTS_TOUCHED");
    addMethodData(sb);

    // Write collected data to CSV
    try {
        FileUtils.writeLines(
                new File(
                        ConfigurationLocator.getJavalancheConfiguration().getOutputDir() + "/class-scores.csv"),
                classScores);
        FileUtils.writeLines(new File(
                ConfigurationLocator.getJavalancheConfiguration().getOutputDir() + "/method-scores.csv"),
                methodScores);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return sb.toString();
}

From source file:com.basistech.lucene.tools.LuceneQueryToolTest.java

@Test
public void testScript() throws Exception {
    List<String> lines = Lists.newArrayList("-q context:bush -o target/out1",
            "-q context:clinton -o target/out2");
    FileUtils.writeLines(new File("target/script.txt"), lines);
    LuceneQueryTool lqt = new LuceneQueryTool(reader);
    lqt.run(new String[] { "%script", "target/script.txt" });
    lines = FileUtils.readLines(new File("target/out1"), "UTF-8");
    assertTrue(Joiner.on(",").join(lines).contains("George"));
    lines = FileUtils.readLines(new File("target/out2"), "UTF-8");
    assertTrue(Joiner.on(",").join(lines).contains("Bill"));
}

From source file:com.blackducksoftware.tools.commonframework.core.config.ConfigurationFileTest.java

/**
 * Test handling of legacy Passwords in plain text with
 * password.isplaintext=true Does not verify that non-password-related lines
 * survive as-is, but testLegacyPasswordPlainTextIsplaintextNotSet() does
 * that.//from w  w  w  . j av a 2 s  .c om
 *
 * @throws Exception
 */
@Test
public void testLegacyPasswordPlainTextIsplaintextTrue() throws Exception {
    final File sourceConfigFile = new File("src/test/resources/psw_encryption/legacy_plain_set.properties");
    final File configFile = File.createTempFile(
            "com.blackducksoftware.tools.commonframework.core.config.ConfigurationFileTest", "test2");
    filesToDelete.add(configFile);
    configFile.deleteOnExit();
    FileUtils.copyFile(sourceConfigFile, configFile);
    final ConfigurationFile cf = new ConfigurationFile(configFile.getAbsolutePath());

    List<String> updatedLines = null;
    if (cf.isInNeedOfUpdate()) {
        updatedLines = cf.saveWithEncryptedPasswords();
    }

    assertTrue(updatedLines.size() > 0);
    final Iterator<String> updatedLinesIter = updatedLines.iterator();
    while (updatedLinesIter.hasNext()) {
        String updatedLine = updatedLinesIter.next();

        // make sure obsolete properties have been removed
        assertFalse(updatedLine.matches("^.*\\.password\\.isplaintext=.*$"));

        // If this is a password, verify that it was encoded, and that the
        // isencrypted=true was inserted after it
        if (updatedLine.startsWith("cc.password=")) {
            assertEquals("cc.password=cc_password", updatedLine);
            updatedLine = updatedLinesIter.next();
            assertEquals("cc.password.isencrypted=false", updatedLine);
        } else if (updatedLine.startsWith("protex.password=")) {
            assertEquals("protex.password=protex_password", updatedLine);
            updatedLine = updatedLinesIter.next();
            assertEquals("protex.password.isencrypted=false", updatedLine);
        } else if (updatedLine.startsWith("connector.0.password=")) {
            assertEquals("connector.0.password=connector_password", updatedLine);
            updatedLine = updatedLinesIter.next();
            assertEquals("connector.0.password.isencrypted=false", updatedLine);
        }
    }

    final File testGeneratedUpdatedFile = File.createTempFile(
            "com.blackducksoftware.tools.commonframework.core.config.ConfigurationFileTest",
            "test2_testGeneratedUpdatedFile");
    filesToDelete.add(testGeneratedUpdatedFile);
    testGeneratedUpdatedFile.deleteOnExit();
    FileUtils.writeLines(testGeneratedUpdatedFile, updatedLines);
    final long csumTestGeneratedFile = FileUtils.checksum(testGeneratedUpdatedFile, new CRC32()).getValue();
    final long csumActualFile = FileUtils.checksum(configFile, new CRC32()).getValue();
    assertEquals(csumTestGeneratedFile, csumActualFile);
}

From source file:com.taobao.android.builder.tools.multidex.mutli.MainDexLister.java

public List<String> getMainDexList(Collection<File> files, File mainDexListFile) {

    GradleVariantConfiguration config = appVariantContext.getVariantConfiguration();

    Set<String> mainDexList = new HashSet<String>();

    //Confusion of the map
    //Map<String, String> classMap = getClassObfMap(config);
    Collection<BaseVariantOutput> collection = appVariantContext.getVariantOutputData();
    File manifest = com.android.utils.FileUtils.join(
            collection.iterator().next().getProcessManifest().getManifestOutputDirectory(),
            new String[] { collection.iterator().next().getDirName(), "AndroidManifest.xml" });

    String applicationName = ManifestFileUtils.getApplicationName(manifest);

    ClassPool classPool = new ClassPool();

    try {/*from w  w w . j a  va2s .  com*/
        for (File file : files) {
            if (file.isFile()) {
                classPool.insertClassPath(file.getAbsolutePath());
            } else {
                classPool.appendClassPath(file.getAbsolutePath());
            }
        }
    } catch (NotFoundException e) {
        throw new GradleException(e.getMessage(), e);
    }

    TBuildConfig tBuildConfig = appVariantContext.getAtlasExtension().getTBuildConfig();

    HashSet handleList = new HashSet<String>();
    Set<String> headClasses = new LinkedHashSet<>();

    headClasses.add(applicationName);
    headClasses.add("android.taobao.atlas.bridge.BridgeApplicationDelegate");
    headClasses.addAll(multiDexConfig.getFirstDexClasses());
    List<String> maindexListClazz = new ArrayList<String>();

    String preLaunchStr = tBuildConfig.getPreLaunch();
    if (!org.apache.commons.lang3.StringUtils.isEmpty(preLaunchStr)) {
        String[] launchArray = preLaunchStr.split("\\|");
        if (launchArray.length > 0) {
            for (String launchItem : launchArray) {
                String[] launchInfo = launchItem.split(":");
                String clazzName = launchInfo[0];
                headClasses.add(clazzName);
            }
        }
    }

    for (String clazz : headClasses) {
        clazz = clazz.replaceAll("\\.", "/") + ".class";
        maindexListClazz.add(clazz);
    }

    for (String headClass : headClasses) {
        addRefClazz(classPool, headClass, mainDexList, handleList, "");
    }

    //get manifest
    for (String newLine : mainDexList) {
        newLine = newLine.replaceAll("\\.", "/") + ".class";
        maindexListClazz.add(newLine);
    }
    for (String className : headClasses) {
        className = className.replaceAll("\\.", "/") + ".class";
        maindexListClazz.add(className);
    }

    if (multiDexConfig.getMainDexListCount() != 0) {

        maindexListClazz = maindexListClazz.subList(0, multiDexConfig.getMainDexListCount());
    }

    try {
        FileUtils.writeLines(mainDexListFile, maindexListClazz);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return maindexListClazz;
}

From source file:com.taobao.android.builder.tools.bundleinfo.BundleInfoUtils.java

private static Map<String, BundleInfo> getBundleInfoMap(AppVariantContext appVariantContext)
        throws IOException {
    File baseBunfleInfoFile = new File(
            appVariantContext.getScope().getGlobalScope().getProject().getProjectDir(),
            "bundleBaseInfoFile.json");

    //??// w ww  . j  a  v a 2 s  .com
    Map<String, BundleInfo> bundleFileMap = Maps.newHashMap();
    if (null != baseBunfleInfoFile && baseBunfleInfoFile.exists() && baseBunfleInfoFile.canRead()) {
        String bundleBaseInfo = FileUtils.readFileToString(baseBunfleInfoFile, "utf-8");
        bundleFileMap = JSON.parseObject(bundleBaseInfo, new TypeReference<Map<String, BundleInfo>>() {
        });
    }

    List<AwbBundle> awbBundles = AtlasBuildContext.androidDependencyTrees
            .get(appVariantContext.getVariantData().getName()).getAwbBundles();

    List<String> duplicatedBundleInfo = new ArrayList<>();
    for (AwbBundle awbBundle : awbBundles) {
        String name = awbBundle.getResolvedCoordinates().getArtifactId();
        File bundleBaseInfoFile = new File(awbBundle.getAndroidLibrary().getFolder(),
                "bundleBaseInfoFile.json");
        if (bundleBaseInfoFile.exists()) {
            String json = FileUtils.readFileToString(bundleBaseInfoFile, "utf-8");
            BundleInfo bundleInfo = JSON.parseObject(json, BundleInfo.class);

            if (bundleFileMap.containsKey(name)) {
                appVariantContext.getProject().getLogger()
                        .error("bundleBaseInfoFile>>>" + name + " has declared bundleBaseInfoFile");
                duplicatedBundleInfo.add(name);
            }

            bundleFileMap.put(name, bundleInfo);
        }
    }

    if (duplicatedBundleInfo.size() > 0) {
        FileUtils.writeLines(new File(appVariantContext.getProject().getBuildDir(),
                "outputs/warning-dupbundleinfo.properties"), duplicatedBundleInfo);
    }

    return bundleFileMap;
}

From source file:com.taobao.android.builder.tasks.app.GenerateAtlasSourceTask.java

@TaskAction
void generate() {

    InjectParam injectParam = getInput();
    boolean supportRemoteComponent = true;
    if (AtlasBuildContext.androidDependencyTrees.get(getVariantName()) != null) {
        List<AndroidLibrary> libraries = AtlasBuildContext.androidDependencyTrees.get(getVariantName())
                .getMainBundle().getAndroidLibraries();
        if (libraries.size() > 0) {
            for (AndroidLibrary library : libraries) {
                MavenCoordinates coordinates = library.getResolvedCoordinates();
                if (coordinates.getArtifactId().equals("atlas_core")
                        && coordinates.getGroupId().equals("com.taobao.android")) {
                    if (coordinates.getVersion().compareTo("5.0.8") < 0) {
                        supportRemoteComponent = false;
                    }/*from w w w .  j a  va2 s  .  c o  m*/
                }
            }
        }
    }
    List<BasicBundleInfo> info = JSON.parseArray(injectParam.bundleInfo, BasicBundleInfo.class);
    File outputSourceGeneratorFile = new File(outputDir,
            "android/taobao/atlas/framework/AtlasBundleInfoGenerator.java");
    StringBuffer infoGeneratorSourceStr = new BundleInfoSourceCreator().createBundleInfoSourceStr(info,
            supportRemoteComponent);
    outputSourceGeneratorFile.getParentFile().mkdirs();
    try {
        FileUtils.writeStringToFile(outputSourceGeneratorFile, infoGeneratorSourceStr.toString());
    } catch (IOException e) {
        throw new GradleException(e.getMessage(), e);
    }

    File outputPropertiesFile = new File(outputDir, "android/taobao/atlas/framework/FrameworkProperties.java");
    List<String> lines = new ArrayList<>();
    outputPropertiesFile.getParentFile().mkdirs();
    lines.add("package android.taobao.atlas.framework;");
    lines.add("public class FrameworkProperties {");

    lines.add("private String version = \"" + injectParam.version + "\";");
    lines.add("public String getVersion() {return version;}");
    String escapeExprBundleInfo = escapeExprSpecialWord(injectParam.bundleInfo);
    if (injectParam.bundleInfo.length() < 65535) {
        lines.add("public static String bundleInfo = \"" + escapeExprBundleInfo + "\";");
        lines.add("public static final boolean compressInfo = false;");
    } else {
        String compressBundleInfo = compressBundleInfo(injectParam.bundleInfo);
        lines.add("public static String bundleInfo = \"" + compressBundleInfo + "\";");
        lines.add("public static final boolean compressInfo = true;");
    }
    //        lines.add("public static String bundleInfo = \"" + escapeExprSpecialWord(injectParam.bundleInfo) + "\";");
    //lines.add("public static String bunleInfo = \"\";");
    if (StringUtils.isNotEmpty(injectParam.autoStartBundles)) {
        lines.add("public static String autoStartBundles = \"" + injectParam.autoStartBundles + "\";");
    }
    if (StringUtils.isNotEmpty(injectParam.blackDialogActivity)) {
        lines.add("public static String blackDialogActivity = \"" + injectParam.blackDialogActivity + "\";");
    }
    lines.add("public static String autoStart = \"" + injectParam.autoStart + "\";");

    if (StringUtils.isNotEmpty(injectParam.preLaunch)) {
        lines.add("public static String preLaunch = \"" + injectParam.preLaunch + "\";");
    }
    if (StringUtils.isNotEmpty(injectParam.group)) {
        lines.add("public static String group = \"" + injectParam.group + "\";");
    }
    lines.add("public static String outApp = \"" + injectParam.outApp + "\";");

    lines.add("}");

    try {

        FileUtils.writeLines(outputPropertiesFile, lines);
        Map output = new HashMap();
        output.put("bundleInfo", JSON.parseArray(injectParam.bundleInfo));
        output.put("autoStartBundles", injectParam.autoStartBundles);
        output.put("preLaunch", injectParam.preLaunch);
        output.put("group", injectParam.group);
        output.put("outApp", injectParam.outApp);
        output.put("unit_tag", injectParam.unit_tag);
        output.put("autoStart", injectParam.autoStart);
        output.put("blackDialogActivity", injectParam.blackDialogActivity);

        FileUtils.write(
                new File(appVariantContext.getProject().getBuildDir(), "outputs/atlasFrameworkProperties.json"),
                JSON.toJSONString(output, true));

    } catch (Exception e) {
        throw new GradleException(e.getMessage(), e);
    }

}

From source file:com.taobao.android.builder.tasks.app.prepare.PreparePackageIdsTask.java

private void writeProperties(Map<String, String> map, File file) {
    file.delete();//www  . ja v a 2 s.  c  om
    file.getParentFile().mkdirs();
    try {
        List<String> lines = new ArrayList<String>();
        for (String key : map.keySet()) {
            lines.add(key + "=" + map.get(key));
        }
        FileUtils.writeLines(file, lines);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.PluginConfigurationServiceDefault.java

protected void saveConfiguration() throws IOException {
    PluginConfigurationServiceDefault.logger.info("Saving the plugin configuration to the XML file.");

    this.configFileWatcher.stop();

    this.configuration.setLastUpdate(new DateTime());

    List<String> lines = new ArrayList<String>(this.configFileHeader);
    lines.add("");

    lines.add("\t<last-update>" + ISODateTimeFormat.dateTime().print(this.configuration.getLastUpdate())
            + "</last-update>");
    lines.add("");

    this.writeSettings(lines);

    this.writeBuildNumbers(lines);

    lines.add("</shared-build-number-config>");
    lines.add("");

    try {/*from w ww .ja  va  2  s .  c o m*/
        FileUtils.writeLines(this.configFile, lines);
    } finally {
        this.initializeFileWatcher();
    }
}