Example usage for java.nio.file StandardOpenOption CREATE

List of usage examples for java.nio.file StandardOpenOption CREATE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption CREATE.

Prototype

StandardOpenOption CREATE

To view the source code for java.nio.file StandardOpenOption CREATE.

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:org.eclipse.mylyn.docs.examples.GenerateEPUB.java

public static void main(String[] args) {

    // clean up from last run
    try {/*w w  w  .  j  av a2  s  .c  o m*/
        Files.delete(Paths.get("loremipsum.html"));
        Files.delete(Paths.get("loremipsum.epub"));
    } catch (IOException e1) {
        /* no worries */ }

    try ( // read MarkDown
            FileReader fr = new FileReader("loremipsum.md");
            // and output HTML
            Writer fw = Files.newBufferedWriter(Paths.get("loremipsum.html"), StandardOpenOption.CREATE)) {

        // generate HTML from markdown
        MarkupParser parser = new MarkupParser();
        parser.setMarkupLanguage(new MarkdownLanguage());
        HtmlDocumentBuilder builder = new HtmlDocumentBuilder(fw);
        parser.setBuilder(builder);
        parser.parse(fr, true);

        // convert any inline equations in the HTML into MathML
        String html = new String(Files.readAllBytes(Paths.get("loremipsum.html")));
        StringBuffer sb = new StringBuffer();
        Matcher m = EQUATION.matcher(html);

        // for each equation
        while (m.find()) {
            // replace the LaTeX code with MathML
            m.appendReplacement(sb, laTeX2MathMl(m.group()));
        }
        m.appendTail(sb);

        // EPUB 2.0 can only handle embedded SVG so we find all referenced
        // SVG files and replace the reference with the actual SVG code
        Document parse = Jsoup.parse(sb.toString(), "UTF-8", Parser.xmlParser());

        Elements select = parse.select("img");
        for (Element element : select) {
            String attr = element.attr("src");
            if (attr.endsWith(".svg")) {
                byte[] svg = Files.readAllBytes(Paths.get(attr));
                element.html(new String(svg));
            }
        }

        // write back the modified HTML-file
        Files.write(Paths.get("loremipsum.html"), sb.toString().getBytes(), StandardOpenOption.WRITE);

        // instantiate a new EPUB version 2 publication
        Publication pub = Publication.getVersion2Instance();

        // include referenced resources (default is false)
        pub.setIncludeReferencedResources(true);

        // title and subject is required
        pub.addTitle("EclipseCon Demo");
        pub.addSubject("EclipseCon Demo");

        // generate table of contents (default is true)
        pub.setGenerateToc(true);
        epub.add(pub);

        // add one chapter
        pub.addItem(Paths.get("loremipsum.html").toFile());

        // create the EPUB
        epub.pack(new File("loremipsum.epub"));

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

}

From source file:edu.cmu.tetrad.cli.search.FgsCli.java

/**
 * @param args the command line arguments
 *//*from   w  w w.j av a 2  s  . c o  m*/
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("fgs", MAIN_OPTIONS);
        return;
    }

    parseArgs(args);

    System.out.println("================================================================================");
    System.out.printf("FGS Discrete (%s)%n", DateTime.printNow());
    System.out.println("================================================================================");

    String argInfo = createArgsInfo();
    System.out.println(argInfo);
    LOGGER.info("=== Starting FGS Discrete: " + Args.toString(args, ' '));
    LOGGER.info(argInfo.trim().replaceAll("\n", ",").replaceAll(" = ", "="));

    Set<String> excludedVariables = (excludedVariableFile == null) ? Collections.EMPTY_SET
            : getExcludedVariables();

    runPreDataValidations(excludedVariables, System.err);
    DataSet dataSet = readInDataSet(excludedVariables);
    runOptionalDataValidations(dataSet, System.err);

    Path outputFile = Paths.get(dirOut.toString(), outputPrefix + ".txt");
    try (PrintStream writer = new PrintStream(
            new BufferedOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE)))) {
        String runInfo = createOutputRunInfo(excludedVariables, dataSet);
        writer.println(runInfo);
        String[] infos = runInfo.trim().replaceAll("\n\n", ";").split(";");
        for (String s : infos) {
            LOGGER.info(s.trim().replaceAll("\n", ",").replaceAll(":,", ":").replaceAll(" = ", "="));
        }

        Graph graph = runFgs(dataSet, writer);

        writer.println();
        writer.println(graph.toString());
    } catch (IOException exception) {
        LOGGER.error("FGS failed.", exception);
        System.err.printf("%s: FGS failed.%n", DateTime.printNow());
        System.out.println("Please see log file for more information.");
        System.exit(-128);
    }
    System.out.printf("%s: FGS finished!  Please see %s for details.%n", DateTime.printNow(),
            outputFile.getFileName().toString());
    LOGGER.info(
            String.format("FGS finished!  Please see %s for details.", outputFile.getFileName().toString()));
}

From source file:edu.cmu.tetrad.cli.search.FgsDiscrete.java

/**
 * @param args the command line arguments
 *///from w w  w  .ja  va2 s  . co  m
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("fgs-discrete", MAIN_OPTIONS);
        return;
    }

    parseArgs(args);

    System.out.println("================================================================================");
    System.out.printf("FGS Discrete (%s)%n", DateTime.printNow());
    System.out.println("================================================================================");

    String argInfo = createArgsInfo();
    System.out.println(argInfo);
    LOGGER.info("=== Starting FGS Discrete: " + Args.toString(args, ' '));
    LOGGER.info(argInfo.trim().replaceAll("\n", ",").replaceAll(" = ", "="));

    Set<String> excludedVariables = (excludedVariableFile == null) ? Collections.EMPTY_SET
            : getExcludedVariables();

    runPreDataValidations(excludedVariables, System.err);

    DataSet dataSet = readInDataSet(excludedVariables);

    runOptionalDataValidations(dataSet, System.err);

    Path outputFile = Paths.get(dirOut.toString(), outputPrefix + ".txt");
    try (PrintStream writer = new PrintStream(
            new BufferedOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE)))) {
        String runInfo = createOutputRunInfo(excludedVariables, dataSet);
        writer.println(runInfo);
        String[] infos = runInfo.trim().replaceAll("\n\n", ";").split(";");
        for (String s : infos) {
            LOGGER.info(s.trim().replaceAll("\n", ",").replaceAll(":,", ":").replaceAll(" = ", "="));
        }

        Graph graph = runFgsDiscrete(dataSet, writer);

        writer.println();
        writer.println(graph.toString());

        if (graphML) {
            writeOutGraphML(graph, Paths.get(dirOut.toString(), outputPrefix + "_graph.txt"));
        }
    } catch (IOException exception) {
        LOGGER.error("FGS Discrete failed.", exception);
        System.err.printf("%s: FGS Discrete failed.%n", DateTime.printNow());
        System.out.println("Please see log file for more information.");
        System.exit(-128);
    }
    System.out.printf("%s: FGS Discrete finished!  Please see %s for details.%n", DateTime.printNow(),
            outputFile.getFileName().toString());
    LOGGER.info(String.format("FGS Discrete finished!  Please see %s for details.",
            outputFile.getFileName().toString()));
}

From source file:net.tirasa.ilgrosso.lngenerator.Main.java

public static void main(final String[] args) throws IOException, URISyntaxException {
    assert args.length > 0 : "No arguments provided";

    File source = new File(args[0]);
    if (!source.isDirectory()) {
        throw new IllegalArgumentException("Not a directory: " + args[0]);
    }/*from w w w.  j  av  a  2s  .c o m*/

    String destPath = args.length > 1 ? args[1] : System.getProperty("java.io.tmpdir");
    File dest = new File(destPath);
    if (!dest.isDirectory() || !dest.canWrite()) {
        throw new IllegalArgumentException("Not a directory, or not writable: " + destPath);
    }

    LOG.debug("Local Maven repo is {}", LOCAL_M2_REPO);
    LOG.debug("Source Path is {}", source.getAbsolutePath());
    LOG.debug("Destination Path is {}", dest.getAbsolutePath());
    LOG.warn("Existing LICENSE and NOTICE files in {} will be overwritten!", dest.getAbsolutePath());

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

    Files.walk(source.toPath()).filter(Files::isRegularFile)
            .map((final Path path) -> path.getFileName().toString())
            .filter((String path) -> path.endsWith(".jar")).sorted().forEach((filename) -> {
                try (Stream<Path> stream = Files.find(LOCAL_M2_REPO_PATH, 10,
                        (path, attr) -> String.valueOf(path.getFileName().toString()).equals(filename))) {

                    String fullPath = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
                    if (fullPath.isEmpty()) {
                        LOG.warn("Could not find {} in the local Maven repo", filename);
                    } else {
                        String path = fullPath.substring(LOCAL_M2_REPO.length() + 1);
                        Gav gav = GAV_CALCULATOR.pathToGav(path);
                        if (gav == null) {
                            LOG.error("Invalid Maven path: {}", path);
                        } else if (!gav.getGroupId().startsWith("org.apache.")
                                && !gav.getGroupId().startsWith("commons-")
                                && !gav.getGroupId().equals("org.codehaus.groovy")
                                && !gav.getGroupId().equals("jakarta-regexp")
                                && !gav.getGroupId().equals("xml-apis") && !gav.getGroupId().equals("batik")) {

                            if (ArrayUtils.contains(CONSOLIDATING_GROUP_IDS, gav.getGroupId())) {
                                keys.add(gav.getGroupId());
                            } else if (gav.getGroupId().startsWith("com.fasterxml.jackson")) {
                                keys.add("com.fasterxml.jackson");
                            } else if (gav.getGroupId().equals("org.webjars.bower") && (gav.getArtifactId()
                                    .startsWith("angular-animate")
                                    || gav.getArtifactId().startsWith("angular-cookies")
                                    || gav.getArtifactId().startsWith("angular-resource")
                                    || gav.getArtifactId().startsWith("angular-sanitize")
                                    || gav.getArtifactId().startsWith("angular-treasure-overlay-spinner"))) {

                                keys.add("org.webjars.bower:angular");
                            } else if (gav.getGroupId().equals("org.webjars.bower")
                                    && gav.getArtifactId().startsWith("angular-translate")) {

                                keys.add("org.webjars.bower:angular-translate");
                            } else if (gav.getGroupId().startsWith("de.agilecoders")) {
                                keys.add("wicket-bootstrap");
                            } else if ("org.webjars".equals(gav.getGroupId())) {
                                if (gav.getArtifactId().startsWith("jquery-ui")) {
                                    keys.add("jquery-ui");
                                } else {
                                    keys.add(gav.getArtifactId());
                                }
                            } else {
                                keys.add(gav.getGroupId() + ":" + gav.getArtifactId());
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.error("While looking for Maven artifacts from the local Maven repo", e);
                }
            });

    final Properties licenses = new Properties();
    licenses.loadFromXML(Main.class.getResourceAsStream("/licenses.xml"));

    final Properties notices = new Properties();
    notices.loadFromXML(Main.class.getResourceAsStream("/notices.xml"));

    BufferedWriter licenseWriter = Files.newBufferedWriter(new File(dest, "LICENSE").toPath(),
            StandardOpenOption.CREATE);
    licenseWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/LICENSE.template").toURI()))));

    BufferedWriter noticeWriter = Files.newBufferedWriter(new File(dest, "NOTICE").toPath(),
            StandardOpenOption.CREATE);
    noticeWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/NOTICE.template").toURI()))));

    EnumSet<LICENSE> outputLicenses = EnumSet.noneOf(LICENSE.class);

    keys.stream().sorted().forEach((final String dependency) -> {
        if (licenses.getProperty(dependency) == null) {
            LOG.error("Could not find license information about {}", dependency);
        } else {
            try {
                licenseWriter.write("\n==\n\nFor " + licenses.getProperty(dependency) + ":\n");

                String depLicense = licenses.getProperty(dependency + ".license");
                if (depLicense == null) {
                    licenseWriter.write("This is licensed under the AL 2.0, see above.");
                } else {
                    LICENSE license = LICENSE.valueOf(depLicense);

                    if (license == LICENSE.PUBLIC_DOMAIN) {
                        licenseWriter.write("This is " + license.getLabel() + ".");
                    } else {
                        licenseWriter.write("This is licensed under the " + license.getLabel());

                        if (outputLicenses.contains(license)) {
                            licenseWriter.write(", see above.");
                        } else {
                            outputLicenses.add(license);

                            licenseWriter.write(":\n\n");
                            licenseWriter.write(new String(Files.readAllBytes(
                                    Paths.get(Main.class.getResource("/LICENSE." + license.name()).toURI()))));
                        }
                    }
                }
                licenseWriter.write('\n');

                if (notices.getProperty(dependency) != null) {
                    noticeWriter.write("\n==\n\n" + notices.getProperty(dependency) + "\n");
                }
            } catch (Exception e) {
                LOG.error("While dealing with {}", dependency, e);
            }
        }
    });

    licenseWriter.close();
    noticeWriter.close();

    LOG.debug("Execution completed successfully, look at {} for the generated LICENSE and NOTICE files",
            dest.getAbsolutePath());
}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {//from  ww  w.  ja  v a 2s  .  com
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:neembuu.uploader.external.HttpUtil.java

public static void update(String url, Path localPath, final Content c) throws IOException {
    NUHttpGet httpGet = new NUHttpGet(url);
    // you cannot use the same http client, or else the program will
    // simply get stuck. This update thing happens concurrently.
    // more than 10-20 plugins might update in parallel.
    // How? user may click button very fast, that's how.
    HttpResponse httpResponse = NUHttpClient.newHttpClient().execute(httpGet);

    try (FileChannel fc = FileChannel.open(localPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        long contentLength = httpResponse.getEntity().getContentLength();
        fc.transferFrom(wrap(httpResponse.getEntity().getContent(), httpResponse.getEntity(), c, contentLength),
                0, contentLength);//from   www  .j  av  a2 s  . com
    }
}

From source file:org.jboss.jbossset.JiraReporterTest.java

@BeforeClass
public static void init() throws Exception {
    List<String> users = new ArrayList<>();
    for (int i = 0; i < NUMBER_OF_USERS; i++)
        users.add("user" + i);
    Files.write(Paths.get("", USERS_FILE_URL), users, StandardOpenOption.CREATE, StandardOpenOption.WRITE);

    Properties p = new Properties();
    p.put("JIRA", "https://issues.jboss.org");
    p.store(new PrintWriter(new File(DOMAIN_FILE_URL)), null);
}

From source file:nls.formacao.matriculador.descarregador.DesCarregadorFicheiro.java

@Override
public void escrever(String info) {
    String nome = Utils.obtemNomeFicheiro("txt");
    try {//from   w  w w .  j  av a 2 s .com
        Path p = Paths.get(nome);
        Files.write(p, info.getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
    } catch (IOException ex) {
        LOG.error("Erro a descarregar registos para o ecr.", ex);
        System.err.println("Erro a descarregar informao para o ecr.");
    }
    System.out.println(String.format("Criado o ficheiro %s.", nome));
}

From source file:org.roda.core.data.utils.JsonUtils.java

public static void writeObjectToFile(Object object, Path file) throws GenericException {
    try {//from w ww  .  ja  va  2 s .c  o m
        String json = getJsonFromObject(object);
        if (json != null) {
            Files.write(file, json.getBytes(), StandardOpenOption.CREATE);
        }
    } catch (IOException e) {
        throw new GenericException("Error writing object, as json, to file", e);
    }
}

From source file:eu.itesla_project.iidm.datasource.Bzip2FileDataSource.java

@Override
public OutputStream newOutputStream(String suffix, String ext, boolean append) throws IOException {
    Path path = getPath(suffix, ext);
    OutputStream os = new BZip2CompressorOutputStream(new BufferedOutputStream(
            Files.newOutputStream(path, append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE)));
    return observer != null ? new ObservableOutputStream(os, path.toString(), observer) : os;
}