Example usage for java.io File isDirectory

List of usage examples for java.io File isDirectory

Introduction

In this page you can find the example usage for java.io File isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Tests whether the file denoted by this abstract pathname is a directory.

Usage

From source file:fr.jayasoft.ivy.Main.java

public static void main(String[] args) throws Exception {
    Options options = getOptions();//from ww  w. j  a va 2  s  .  c o  m

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("?")) {
            usage(options);
            return;
        }

        if (line.hasOption("debug")) {
            Message.init(new DefaultMessageImpl(Message.MSG_DEBUG));
        } else if (line.hasOption("verbose")) {
            Message.init(new DefaultMessageImpl(Message.MSG_VERBOSE));
        } else if (line.hasOption("warn")) {
            Message.init(new DefaultMessageImpl(Message.MSG_WARN));
        } else if (line.hasOption("error")) {
            Message.init(new DefaultMessageImpl(Message.MSG_ERR));
        } else {
            Message.init(new DefaultMessageImpl(Message.MSG_INFO));
        }

        boolean validate = line.hasOption("novalidate") ? false : true;

        Ivy ivy = new Ivy();
        ivy.addAllVariables(System.getProperties());
        if (line.hasOption("m2compatible")) {
            ivy.setVariable("ivy.default.configuration.m2compatible", "true");
        }

        configureURLHandler(line.getOptionValue("realm", null), line.getOptionValue("host", null),
                line.getOptionValue("username", null), line.getOptionValue("passwd", null));

        String confPath = line.getOptionValue("conf", "");
        if ("".equals(confPath)) {
            ivy.configureDefault();
        } else {
            File conffile = new File(confPath);
            if (!conffile.exists()) {
                error(options, "ivy configuration file not found: " + conffile);
            } else if (conffile.isDirectory()) {
                error(options, "ivy configuration file is not a file: " + conffile);
            }
            ivy.configure(conffile);
        }

        File cache = new File(
                ivy.substitute(line.getOptionValue("cache", ivy.getDefaultCache().getAbsolutePath())));
        if (!cache.exists()) {
            cache.mkdirs();
        } else if (!cache.isDirectory()) {
            error(options, cache + " is not a directory");
        }

        String[] confs;
        if (line.hasOption("confs")) {
            confs = line.getOptionValues("confs");
        } else {
            confs = new String[] { "*" };
        }

        File ivyfile;
        if (line.hasOption("dependency")) {
            String[] dep = line.getOptionValues("dependency");
            if (dep.length != 3) {
                error(options,
                        "dependency should be expressed with exactly 3 arguments: organisation module revision");
            }
            ivyfile = File.createTempFile("ivy", ".xml");
            ivyfile.deleteOnExit();
            DefaultModuleDescriptor md = DefaultModuleDescriptor
                    .newDefaultInstance(ModuleRevisionId.newInstance(dep[0], dep[1] + "-caller", "working"));
            DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md,
                    ModuleRevisionId.newInstance(dep[0], dep[1], dep[2]), false, false, true);
            for (int i = 0; i < confs.length; i++) {
                dd.addDependencyConfiguration("default", confs[i]);
            }
            md.addDependency(dd);
            XmlModuleDescriptorWriter.write(md, ivyfile);
            confs = new String[] { "default" };
        } else {
            ivyfile = new File(ivy.substitute(line.getOptionValue("ivy", "ivy.xml")));
            if (!ivyfile.exists()) {
                error(options, "ivy file not found: " + ivyfile);
            } else if (ivyfile.isDirectory()) {
                error(options, "ivy file is not a file: " + ivyfile);
            }
        }

        ResolveReport report = ivy.resolve(ivyfile.toURL(), null, confs, cache, null, validate, false, true,
                line.hasOption("useOrigin"), null);
        if (report.hasError()) {
            System.exit(1);
        }
        ModuleDescriptor md = report.getModuleDescriptor();

        if (confs.length == 1 && "*".equals(confs[0])) {
            confs = md.getConfigurationsNames();
        }
        if (line.hasOption("retrieve")) {
            String retrievePattern = ivy.substitute(line.getOptionValue("retrieve"));
            if (retrievePattern.indexOf("[") == -1) {
                retrievePattern = retrievePattern + "/lib/[conf]/[artifact].[ext]";
            }
            ivy.retrieve(md.getModuleRevisionId().getModuleId(), confs, cache, retrievePattern, null, null,
                    line.hasOption("sync"), line.hasOption("useOrigin"));
        }
        if (line.hasOption("cachepath")) {
            outputCachePath(ivy, cache, md, confs, line.getOptionValue("cachepath", "ivycachepath.txt"));
        }

        if (line.hasOption("revision")) {
            ivy.deliver(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                    cache, ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")),
                    ivy.substitute(line.getOptionValue("status", "release")), null,
                    new DefaultPublishingDRResolver(), validate);
            if (line.hasOption("publish")) {
                ivy.publish(md.getResolvedModuleRevisionId(), ivy.substitute(line.getOptionValue("revision")),
                        cache,
                        ivy.substitute(line.getOptionValue("publishpattern",
                                "distrib/[type]s/[artifact]-[revision].[ext]")),
                        line.getOptionValue("publish"),
                        ivy.substitute(line.getOptionValue("deliverto", "ivy-[revision].xml")), validate);

            }
        }
        if (line.hasOption("main")) {
            invoke(ivy, cache, md, confs, line.getOptionValue("main"), line.getOptionValues("args"));
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());

        usage(options);
    }
}

From source file:apps.LuceneIndexer.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("i", null, true, "input file");
    options.addOption("o", null, true, "output directory");
    options.addOption("r", null, true, "optional output TREC-format QREL file");

    options.addOption("bm25_b", null, true, "BM25 parameter: b");
    options.addOption("bm25_k1", null, true, "BM25 parameter: k1");
    options.addOption("bm25fixed", null, false, "use the fixed BM25 similarity");

    Joiner commaJoin = Joiner.on(',');
    Joiner spaceJoin = Joiner.on(' ');

    options.addOption("source_type", null, true,
            "document source type: " + commaJoin.join(SourceFactory.getDocSourceList()));

    // If you increase this value, you may need to modify the following line in *.sh file
    // export MAVEN_OPTS="-Xms8192m -server"
    double ramBufferSizeMB = 1024 * 8; // 8 GB

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    IndexWriter indexWriter = null;//w ww.j  a va2  s  .co  m
    BufferedWriter qrelWriter = null;

    int docNum = 0;

    try {
        CommandLine cmd = parser.parse(options, args);

        String inputFileName = null, outputDirName = null, qrelFileName = null;

        if (cmd.hasOption("i")) {
            inputFileName = cmd.getOptionValue("i");
        } else {
            Usage("Specify 'input file'", options);
        }

        if (cmd.hasOption("o")) {
            outputDirName = cmd.getOptionValue("o");
        } else {
            Usage("Specify 'index directory'", options);
        }

        if (cmd.hasOption("r")) {
            qrelFileName = cmd.getOptionValue("r");
        }

        String sourceName = cmd.getOptionValue("source_type");

        if (sourceName == null)
            Usage("Specify document source type", options);

        if (qrelFileName != null)
            qrelWriter = new BufferedWriter(new FileWriter(qrelFileName));

        File outputDir = new File(outputDirName);
        if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                System.out.println("couldn't create " + outputDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!outputDir.isDirectory()) {
            System.out.println(outputDir.getAbsolutePath() + " is not a directory!");
            System.exit(1);
        }
        if (!outputDir.canWrite()) {
            System.out.println("Can't write to " + outputDir.getAbsolutePath());
            System.exit(1);
        }

        boolean useFixedBM25 = cmd.hasOption("bm25fixed");

        float bm25_k1 = UtilConst.BM25_K1_DEFAULT, bm25_b = UtilConst.BM25_B_DEFAULT;

        if (cmd.hasOption("bm25_k1")) {
            try {
                bm25_k1 = Float.parseFloat(cmd.getOptionValue("bm25_k1"));
            } catch (NumberFormatException e) {
                Usage("Wrong format for 'bm25_k1'", options);
            }
        }

        if (cmd.hasOption("bm25_b")) {
            try {
                bm25_b = Float.parseFloat(cmd.getOptionValue("bm25_b"));
            } catch (NumberFormatException e) {
                Usage("Wrong format for 'bm25_b'", options);
            }
        }

        EnglishAnalyzer analyzer = new EnglishAnalyzer();
        FSDirectory indexDir = FSDirectory.open(Paths.get(outputDirName));
        IndexWriterConfig indexConf = new IndexWriterConfig(analyzer);

        /*
            OpenMode.CREATE creates a new index or overwrites an existing one.
            https://lucene.apache.org/core/6_0_0/core/org/apache/lucene/index/IndexWriterConfig.OpenMode.html#CREATE
        */
        indexConf.setOpenMode(OpenMode.CREATE);
        indexConf.setRAMBufferSizeMB(ramBufferSizeMB);

        System.out.println(String.format("BM25 parameters k1=%f b=%f ", bm25_k1, bm25_b));

        if (useFixedBM25) {
            System.out.println(String.format("Using fixed BM25Simlarity, k1=%f b=%f", bm25_k1, bm25_b));
            indexConf.setSimilarity(new BM25SimilarityFix(bm25_k1, bm25_b));
        } else {
            System.out.println(String.format("Using Lucene BM25Similarity, k1=%f b=%f", bm25_k1, bm25_b));
            indexConf.setSimilarity(new BM25Similarity(bm25_k1, bm25_b));
        }

        indexWriter = new IndexWriter(indexDir, indexConf);

        DocumentSource inpDocSource = SourceFactory.createDocumentSource(sourceName, inputFileName);
        DocumentEntry inpDoc = null;
        TextCleaner textCleaner = new TextCleaner(null);

        while ((inpDoc = inpDocSource.next()) != null) {
            ++docNum;

            Document luceneDoc = new Document();
            ArrayList<String> cleanedToks = textCleaner.cleanUp(inpDoc.mDocText);
            String cleanText = spaceJoin.join(cleanedToks);

            //        System.out.println(inpDoc.mDocId);
            //        System.out.println(cleanText);
            //        System.out.println("==============================");

            luceneDoc.add(new StringField(UtilConst.FIELD_ID, inpDoc.mDocId, Field.Store.YES));
            luceneDoc.add(new TextField(UtilConst.FIELD_TEXT, cleanText, Field.Store.YES));
            indexWriter.addDocument(luceneDoc);

            if (inpDoc.mIsRel != null && qrelWriter != null) {
                saveQrelOneEntry(qrelWriter, inpDoc.mQueryId, inpDoc.mDocId, inpDoc.mIsRel ? MAX_GRADE : 0);
            }
            if (docNum % 1000 == 0)
                System.out.println(String.format("Indexed %d documents", docNum));

        }

    } catch (ParseException e) {
        e.printStackTrace();
        Usage("Cannot parse arguments" + e, options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    } finally {
        System.out.println(String.format("Indexed %d documents", docNum));

        try {
            if (null != indexWriter)
                indexWriter.close();
            if (null != qrelWriter)
                qrelWriter.close();
        } catch (IOException e) {
            System.err.println("IO exception: " + e);
            e.printStackTrace();
        }
    }
}

From source file:com.junoyoon.BullsHtml.java

/**
 * @param args//from  w w w .  j  a  v a  2 s.c o  m
 */
public static void main(String[] args) {
    final CommandLineParser clp = new DefaultParser();
    CommandLine line = null;

    // parse CLI options
    try {
        line = clp.parse(BullsHtml.OPTS, args);
    } catch (ParseException e) {
        printMessage("Invalid options");
        usage();
        return;
    }
    String sourceEncoding = BullsHtml.enc;
    // get encoding option
    if (line.hasOption("e")) {
        sourceEncoding = line.getOptionValue("e");
    }
    // print usage if -h
    if (line.hasOption("h")) {
        usage();
    }

    if (line.hasOption("v")) {
        BullsHtml.verbose = true;
    }
    String covfile = null;
    if (line.hasOption("f")) {
        covfile = line.getOptionValue("f");
        if (!new File(covfile).exists()) {
            printErrorAndExit(covfile + " does not exists");
        }
    }

    String outputPath = ".";

    if (line.getArgs().length != 1) {
        printErrorAndExit("please provide the html output directory");
    }
    outputPath = line.getArgs()[0];
    File o = new File(outputPath);
    if (!o.exists()) {
        if (!o.mkdirs()) {
            printErrorAndExit(outputPath + " directory can be not created.");
        }
    } else if (!o.isDirectory()) {
        printErrorAndExit(outputPath + " is not directory.");
    } else if (!o.canWrite()) {
        printErrorAndExit(outputPath + " is not writable.");
    }
    BullsHtml bullshtml = new BullsHtml();
    bullshtml.process(covfile);
    if (BullsHtml.baseList.isEmpty()) {
        printErrorAndExit(
                "No coverage was recorded in cov file. please check if src is compiled with coverage on.");
    }
    try {
        bullshtml.copyResources(outputPath);
    } catch (Exception e) {
        printErrorAndExit("The output " + outputPath + " is not writable.", e);
    }
    BullsHtml.sourceEncoding = Encoding.getEncoding(sourceEncoding);
    bullshtml.generateHtml(o);
    bullshtml.generateCloverXml(o);
}

From source file:main.java.RMDupper.java

public static void main(String[] args) throws IOException {
    System.err.println("DeDup v" + VERSION);
    // the command line parameters
    Options helpOptions = new Options();
    helpOptions.addOption("h", "help", false, "show this help page");
    Options options = new Options();
    options.addOption("h", "help", false, "show this help page");
    options.addOption("i", "input", true,
            "the input file if this option is not specified,\nthe input is expected to be piped in");
    options.addOption("o", "output", true, "the output folder. Has to be specified if input is set.");
    options.addOption("m", "merged", false,
            "the input only contains merged reads.\n If this option is specified read names are not examined for prefixes.\n Both the start and end of the aligment are considered for all reads.");
    options.addOption("v", "version", false, "the version of DeDup.");
    HelpFormatter helpformatter = new HelpFormatter();
    CommandLineParser parser = new BasicParser();
    try {/*from   w  ww . j av  a 2  s .  c  o m*/
        CommandLine cmd = parser.parse(helpOptions, args);
        if (cmd.hasOption('h')) {
            helpformatter.printHelp(CLASS_NAME, options);
            System.exit(0);
        }
    } catch (ParseException e1) {
    }

    String input = "";
    String outputpath = "";
    Boolean merged = Boolean.FALSE;
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('i')) {
            input = cmd.getOptionValue('i');
            piped = false;
        }
        if (cmd.hasOption('o')) {
            outputpath = cmd.getOptionValue('o');
        }
        if (cmd.hasOption('m')) {
            merged = Boolean.TRUE;
        }
        if (cmd.hasOption('v')) {
            System.out.println("DeDup v" + VERSION);
            System.exit(0);
        }
    } catch (ParseException e) {
        helpformatter.printHelp(CLASS_NAME, options);
        System.err.println(e.getMessage());
        System.exit(0);
    }
    DecimalFormat df = new DecimalFormat("##.##");

    if (piped) {
        RMDupper rmdup = new RMDupper(System.in, System.out, merged);
        rmdup.readSAMFile();

        System.err.println("We are in piping mode!");
        System.err.println("Total reads: " + rmdup.dupStats.total + "\n");
        System.err.println("Reverse removed: " + rmdup.dupStats.removed_reverse + "\n");
        System.err.println("Forward removed: " + rmdup.dupStats.removed_forward + "\n");
        System.err.println("Merged removed: " + rmdup.dupStats.removed_merged + "\n");
        System.err.println("Total removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_merged
                + rmdup.dupStats.removed_reverse) + "\n");
        if (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_forward
                + rmdup.dupStats.removed_reverse == 0) {
            System.err.println("Duplication Rate: " + df.format(0.00));
        } else {
            System.err.println("Duplication Rate: "
                    + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse
                            + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total));
        }

    } else {
        if (outputpath.length() == 0) {
            System.err.println("The output folder has to be specified");
            helpformatter.printHelp(CLASS_NAME, options);
            System.exit(0);
        }

        //Check whether we have a directory as output path, else produce error message and quit!

        File f = new File(outputpath);
        if (!f.isDirectory()) {
            System.err.println("The output folder should be a folder and not a file!");
            System.exit(0);
        }

        File inputFile = new File(input);
        File outputFile = new File(
                outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + "_rmdup.bam");
        File outputlog = new File(
                outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + ".log");
        File outputhist = new File(
                outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + ".hist");

        try {
            FileWriter fw = new FileWriter(outputlog);
            FileWriter histfw = new FileWriter(outputhist);
            BufferedWriter bfw = new BufferedWriter(fw);
            BufferedWriter histbfw = new BufferedWriter(histfw);

            RMDupper rmdup = new RMDupper(inputFile, outputFile, merged);
            rmdup.readSAMFile();
            rmdup.inputSam.close();
            rmdup.outputSam.close();

            bfw.write("Total reads: " + rmdup.dupStats.total + "\n");
            bfw.write("Reverse removed: " + rmdup.dupStats.removed_reverse + "\n");
            bfw.write("Forward removed: " + rmdup.dupStats.removed_forward + "\n");
            bfw.write("Merged removed: " + rmdup.dupStats.removed_merged + "\n");
            bfw.write("Total removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_merged
                    + rmdup.dupStats.removed_reverse) + "\n");
            bfw.write("Duplication Rate: "
                    + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse
                            + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total));
            bfw.flush();
            bfw.close();

            histbfw.write(rmdup.oc.getHistogram());
            histbfw.flush();
            histbfw.close();

            System.out.println("Total reads: " + rmdup.dupStats.total + "\n");
            System.out.println("Unmerged removed: "
                    + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_reverse) + "\n");
            System.out.println("Merged removed: " + rmdup.dupStats.removed_merged + "\n");
            System.out.println("Total removed: " + (rmdup.dupStats.removed_forward
                    + rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse) + "\n");
            if (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_forward
                    + rmdup.dupStats.removed_reverse == 0) {
                System.out.println("Duplication Rate: " + df.format(0.00));
            } else {
                System.out.println("Duplication Rate: "
                        + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse
                                + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.turn.ttorrent.cli.TorrentMain.java

/**
 * Torrent reader and creator.//  w w  w  . j av  a2  s.com
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option pieceLength = parser.addIntegerOption('l', "length");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Integer pieceLengthVal = (Integer) parser.getOptionValue(pieceLength);
    if (pieceLengthVal == null) {
        pieceLengthVal = Torrent.DEFAULT_PIECE_LENGTH;
    } else {
        pieceLengthVal = pieceLengthVal * 1024;
    }
    logger.info("Using piece length of {} bytes.", pieceLengthVal);

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                List<File> files = new ArrayList<File>(
                        FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE));
                Collections.sort(files);
                torrent = Torrent.create(source, files, pieceLengthVal, announceList, creator);
            } else {
                torrent = Torrent.create(source, pieceLengthVal, announceList, creator);
            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:it.univpm.deit.semedia.musicuri.utils.experimental.LambdaCalculator.java

public static void main(String[] args) throws Exception {

    //*****************************************************************************
    //*************************   F I L E   I N P U T   ***************************
    //*****************************************************************************

    if ((args.length == 1) && (new File(args[0]).exists())) {
        // get the file's canonical path
        File givenHandle = new File(args[0]);
        String queryAudioCanonicalPath = givenHandle.getCanonicalPath();
        System.out.println("Input: " + queryAudioCanonicalPath);

        //PerformanceStatistic tempStat;
        SummaryStatistics lambdaSummary = SummaryStatistics.newInstance();

        if (givenHandle.isDirectory()) {

            File[] list = givenHandle.listFiles();
            if (list.length == 0) {
                System.out.println("Directory is empty");
                return;
            } else {
                ArrayList allStats = new ArrayList();
                File currentFile;
                for (int i = 0; i < list.length; i++) {
                    currentFile = list[i];
                    try {
                        if (Toolset.isSupportedAudioFile(currentFile)) {
                            System.out.println("\nCalculating optimal lambda : " + currentFile.getName());
                            lambdaSummary.addValue(getBestLambda(new MusicURIQuery(currentFile)));
                        }/*from   www  .  j  a  v  a2  s  .com*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //               System.out.println("\n\nStatistics for Test Case: " + queryAudioCanonicalPath);
                //               mergeStatistics(allStats);
            }
        }
        if (givenHandle.isFile()) {
            if (Toolset.isSupportedAudioFile(givenHandle)) {
                //               tempStat = getBestLambda (new MusicURIQuery(givenHandle));
                //               if (tempStat!=null)
                //               {
                //                  //tempStat.printStatistics();
                //                  ArrayList allStats = new ArrayList();
                //                  allStats.add(tempStat);
                //                  mergeStatistics(allStats);
                //               }
                //               else 
                //                  System.out.println("Error in identification ");
            }
        }

    } //end if
    else {
        System.err.println("LambdaCalculator");
        System.err.println("Usage: java tester.LambdaCalculator {directory}");
    }

}

From source file:com.appeligo.ccdataindexer.Indexer.java

public static void main(String args[]) throws Exception {
    ConfigurationService.setRootDir(new File("config"));
    ConfigurationService.setEnvName("live");
    ConfigurationService.init();//from   w  w  w .j a va 2s  .c o  m
    if (args.length < 4 || args.length > 5) {
        usage();
        System.exit(-1);
    }
    File file = new File(args[0]);
    if (!file.isDirectory()) {
        usage();
        System.exit(-1);
    }

    Date date = null;
    if (args.length == 5) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        date = format.parse(args[4]);
    }
    long now = System.currentTimeMillis();
    String epgUrl = args[1];
    String indexLocation = args[2];
    String compositeIndexLocation = args[3];
    if (indexLocation.toLowerCase().trim().equals("null")) {
        indexLocation = null;
    }
    if (compositeIndexLocation.toLowerCase().trim().equals("null")) {
        compositeIndexLocation = null;
    }
    if (indexLocation == null && compositeIndexLocation == null) {
        log.error("At least one of indexLocation or compositeIndexLocation cannot be null.");
        usage();
    }
    Indexer indexer = new Indexer(file, epgUrl, indexLocation, compositeIndexLocation);
    if (date != null) {
        indexer.setAfterDate(date);
    }
    if (date == null) {
        log.info("Processing all files");
    } else {
        log.info("Processing all files after " + date + " sanityCheck " + indexer.getAfterDate());

    }
    int count = indexer.index();
    long after = System.currentTimeMillis();
    log.info("Processing took " + ((after - now) / (60 * 1000)) + " minutes to index the programs.");
    log.info("Time spent looking up scheduled programs in epg: " + (lookupTime / (60 * 1000)) + " minutes");

    log.info("Indexed " + count + " programs");
}

From source file:com.act.lcms.db.io.ExportStandardIonResultsFromDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//  ww w  .  ja  v  a 2s.  c  o  m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(ExportStandardIonResultsFromDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ExportStandardIonResultsFromDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                null, true);
        return;
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        List<String> chemicalNames = new ArrayList<>();
        if (cl.hasOption(OPTION_CONSTRUCT)) {
            // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals
            List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils
                    .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));

            for (Pair<ChemicalAssociatedWithPathway, Double> pair : productMasses) {
                chemicalNames.add(pair.getLeft().getChemical());
            }
        }

        if (cl.hasOption(OPTION_CHEMICALS)) {
            chemicalNames.addAll(Arrays.asList(cl.getOptionValues(OPTION_CHEMICALS)));
        }

        if (chemicalNames.size() == 0) {
            System.err.format("No chemicals can be found from the input query.\n");
            System.exit(-1);
        }

        List<String> standardIonHeaderFields = new ArrayList<String>() {
            {
                add(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name());
                add(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name());
                add(STANDARD_ION_HEADER_FIELDS.MANUAL_PICK.name());
                add(STANDARD_ION_HEADER_FIELDS.AUTHOR.name());
                add(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name());
                add(STANDARD_ION_HEADER_FIELDS.NOTE.name());
            }
        };

        String outAnalysis;
        if (cl.hasOption(OPTION_OUTPUT_PREFIX)) {
            outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + TSV_FORMAT;
        } else {
            outAnalysis = String.join("-", chemicalNames) + "." + TSV_FORMAT;
        }

        File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
        if (!lcmsDir.isDirectory()) {
            System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
            HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                    null, true);
            System.exit(1);
        }

        String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);

        TSVWriter<String, String> resultsWriter = new TSVWriter<>(standardIonHeaderFields);
        resultsWriter.open(new File(outAnalysis));

        // For each chemical, create a TSV row and a corresponding diagnostic plot
        for (String chemicalName : chemicalNames) {
            List<String> graphLabels = new ArrayList<>();
            List<Double> yMaxList = new ArrayList<>();

            String outData = plottingDirectory + "/" + chemicalName + ".data";
            String outImg = plottingDirectory + "/" + chemicalName + ".pdf";

            // For each diagnostic plot, open a new file stream.
            try (FileOutputStream fos = new FileOutputStream(outData)) {

                List<StandardIonResult> getResultByChemicalName = StandardIonResult.getByChemicalName(db,
                        chemicalName);

                if (getResultByChemicalName != null && getResultByChemicalName.size() > 0) {

                    // PART 1: Get the best metlin ion across all standard ion results for a given chemical
                    String bestGlobalMetlinIon = AnalysisHelper
                            .scoreAndReturnBestMetlinIonFromStandardIonResults(getResultByChemicalName,
                                    new HashMap<>(), true, true);

                    // PART 2: Plot all the graphs related to the chemical. The plots are structured as follows:
                    //
                    // Page 1: All graphs (water, MeOH, Yeast) for Global ion picked (best ion among ALL standard ion runs for
                    // the given chemical) by the algorithm
                    // Page 2: All graphs for M+H
                    // Page 3: All graphs for Local ions picked (best ion within a SINGLE standard ion run) + negative controls
                    // for Yeast.
                    //
                    // Each page is demarcated by a blank graph.

                    // Arrange results based on media
                    Map<String, List<StandardIonResult>> categories = StandardIonResult
                            .categorizeListOfStandardWellsByMedia(db, getResultByChemicalName);

                    // This set contains all the best metlin ions corresponding to all the standard ion runs.
                    Set<String> bestLocalIons = new HashSet<>();
                    bestLocalIons.add(bestGlobalMetlinIon);
                    bestLocalIons.add(DEFAULT_ION);

                    for (StandardIonResult result : getResultByChemicalName) {
                        bestLocalIons.add(result.getBestMetlinIon());
                    }

                    // We sort the best local ions are follows:
                    // 1) Global best ion spectra 2) M+H spectra 3) Local best ion spectra
                    List<String> bestLocalIonsArray = new ArrayList<>(bestLocalIons);
                    Collections.sort(bestLocalIonsArray, new Comparator<String>() {
                        @Override
                        public int compare(String o1, String o2) {
                            if (o1.equals(bestGlobalMetlinIon) && !o2.equals(bestGlobalMetlinIon)) {
                                return -1;
                            } else if (o1.equals(DEFAULT_ION) && !o2.equals(bestGlobalMetlinIon)) {
                                return -1;
                            } else {
                                return 1;
                            }
                        }
                    });

                    // This variable stores the index of the array at which all the remaining spectra are contained in one
                    // page. This happens right after the M+H ion spectra.
                    Integer combineAllSpectraIntoPageThreeFromIndex = 0;
                    for (int i = 0; i < bestLocalIonsArray.size(); i++) {
                        if (bestLocalIonsArray.get(i).equals(DEFAULT_ION)) {
                            combineAllSpectraIntoPageThreeFromIndex = i + 1;
                        }
                    }

                    for (int i = 0; i < bestLocalIonsArray.size(); i++) {

                        String ion = bestLocalIonsArray.get(i);
                        for (Map.Entry<String, List<StandardIonResult>> mediaToListOfIonResults : categories
                                .entrySet()) {

                            for (StandardIonResult result : mediaToListOfIonResults.getValue()) {

                                // For every standard ion result, we plot the best global metlin ion and M+H. These plots are in the
                                // pages 1 and 2. For all page 3 (aka miscellaneous spectra), we only plot the best local ion
                                // corresponding to it's spectra and not some other graph's spectra. In the below condition,
                                // we reach the page 3 case with not the same best ion as the spectra, in which case we just continue
                                // and not draw anything on the page.
                                if (i >= combineAllSpectraIntoPageThreeFromIndex
                                        && !(result.getBestMetlinIon().equals(ion))) {
                                    continue;
                                }

                                StandardWell positiveWell = StandardWell.getInstance().getById(db,
                                        result.getStandardWellId());
                                String positiveControlChemical = positiveWell.getChemical();

                                ScanData<StandardWell> encapsulatedDataForPositiveControl = AnalysisHelper
                                        .getScanDataForWell(db, lcmsDir, positiveWell, positiveControlChemical,
                                                positiveControlChemical);

                                Set<String> singletonSet = Collections.singleton(ion);
                                String additionalInfo = generateAdditionalLabelInformation(positiveWell, result,
                                        ion);

                                List<String> labels = AnalysisHelper
                                        .writeScanData(fos, lcmsDir, MAX_INTENSITY,
                                                encapsulatedDataForPositiveControl, false, false, singletonSet)
                                        .stream().map(label -> label + additionalInfo)
                                        .collect(Collectors.toList());

                                yMaxList.add(encapsulatedDataForPositiveControl.getMs1ScanResults()
                                        .getMaxIntensityForIon(ion));

                                List<String> negativeLabels = null;
                                // Only do the negative control in the miscellaneous page (page 3) and if the well is in yeast media.
                                if (mediaToListOfIonResults.getKey()
                                        .equals(StandardWell.MEDIA_TYPE.YEAST.name())
                                        && (i >= combineAllSpectraIntoPageThreeFromIndex
                                                && (result.getBestMetlinIon().equals(ion)))) {
                                    //TODO: Change the representative negative well to one that displays the highest noise in the future.
                                    // For now, we just use the first index among the negative wells.
                                    int representativeIndex = 0;
                                    StandardWell representativeNegativeControlWell = StandardWell.getInstance()
                                            .getById(db, result.getNegativeWellIds().get(representativeIndex));

                                    ScanData encapsulatedDataForNegativeControl = AnalysisHelper
                                            .getScanDataForWell(db, lcmsDir, representativeNegativeControlWell,
                                                    positiveWell.getChemical(),
                                                    representativeNegativeControlWell.getChemical());

                                    String negativePlateAdditionalInfo = generateAdditionalLabelInformation(
                                            representativeNegativeControlWell, null, null);

                                    negativeLabels = AnalysisHelper.writeScanData(fos, lcmsDir, MAX_INTENSITY,
                                            encapsulatedDataForNegativeControl, false, false, singletonSet)
                                            .stream().map(label -> label + negativePlateAdditionalInfo)
                                            .collect(Collectors.toList());

                                    yMaxList.add(encapsulatedDataForNegativeControl.getMs1ScanResults()
                                            .getMaxIntensityForIon(ion));
                                }

                                graphLabels.addAll(labels);

                                if (negativeLabels != null) {
                                    graphLabels.addAll(negativeLabels);
                                }
                            }
                        }

                        // Add a blank graph to demarcate pages.
                        if (i < combineAllSpectraIntoPageThreeFromIndex) {
                            graphLabels.addAll(AnalysisHelper.writeScanData(fos, lcmsDir, 0.0, BLANK_SCAN,
                                    false, false, new HashSet<>()));
                            yMaxList.add(0.0d);
                        }
                    }

                    // We need to pass the yMax values as an array to the Gnuplotter.
                    Double fontScale = null;
                    if (cl.hasOption(FONT_SCALE)) {
                        try {
                            fontScale = Double.parseDouble(cl.getOptionValue(FONT_SCALE));
                        } catch (IllegalArgumentException e) {
                            System.err.format("Argument for font-scale must be a floating point number.\n");
                            System.exit(1);
                        }
                    }

                    Double[] yMaxes = yMaxList.toArray(new Double[yMaxList.size()]);
                    Gnuplotter plotter = fontScale == null ? new Gnuplotter() : new Gnuplotter(fontScale);
                    plotter.plot2D(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]), "time",
                            null, "intensity", "pdf", null, null, yMaxes, outImg + ".gnuplot");

                    Map<String, String> row = new HashMap<>();
                    row.put(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name(), chemicalName);
                    row.put(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name(), bestGlobalMetlinIon);
                    row.put(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name(), outImg);

                    resultsWriter.append(row);
                    resultsWriter.flush();
                }
            }
        }

        resultsWriter.flush();
        resultsWriter.close();
    }
}

From source file:mujava.cli.genmutes.java

public static void main(String[] args) throws Exception {
    // System.out.println("test");
    genmutesCom jct = new genmutesCom();
    String[] argv = { "-all", "-debug", "Flower" }; // development use, when release,
    // comment out this line
    JCommander jCommander = new JCommander(jct, args);

    // check session name
    if (jct.getParameters().size() > 1) {
        Util.Error("Has more parameters than needed.");
        return;/*from ww w.ja  v  a  2 s . c  o  m*/
    }

    // set session name
    String sessionName = jct.getParameters().get(0);

    muJavaHomePath = Util.loadConfig();
    // check if debug mode
    if (jct.isDebug()) {
        Util.debug = true;
    }

    // get all existing session name
    File folder = new File(muJavaHomePath);
    // check if the config file has defined the correct folder
    if (!folder.isDirectory()) {
        Util.Error("ERROR: cannot locate the folder specified in mujava.config");
        return;
    }
    File[] listOfFiles = folder.listFiles();
    // null checking
    // check the specified folder has files or not
    if (listOfFiles == null) {
        Util.Error("ERROR: no files in the muJava home folder: " + muJavaHomePath);
        return;
    }
    List<String> fileNameList = new ArrayList<>();
    for (File file : listOfFiles) {
        fileNameList.add(file.getName());
    }

    // check if session is already created.
    if (!fileNameList.contains(sessionName)) {
        Util.Error("Session does not exist.");
        return;

    }

    // get all files in the session
    String[] file_list = new String[1];
    // if(jct.getD())
    // {
    File sessionFolder = new File(muJavaHomePath + "/" + sessionName + "/src");
    File[] listOfFilesInSession = sessionFolder.listFiles();
    file_list = new String[listOfFilesInSession.length];
    for (int i = 0; i < listOfFilesInSession.length; i++) {
        file_list[i] = listOfFilesInSession[i].getName();
    }

    // get all mutation operators selected
    HashMap<String, List<String>> ops = new HashMap<String, List<String>>(); // used
    // for
    // add
    // random
    // percentage
    // and
    // maximum

    String[] paras = new String[] { "1", "0" };
    if (jct.getAll()) // all is selected, add all operators
    {

        // if all is selected, all mutation operators are added
        ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
        // ops.put("SDL", jct.getAll());

    } else { // if not all, add selected ops to the list
        if (jct.getAORB()) {
            ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAORS()) {
            ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAOIU()) {
            ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAOIS()) {
            ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAODU()) {
            ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAODS()) {
            ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getROR()) {
            ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOR()) {
            ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOD()) {
            ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOI()) {
            ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getSOR()) {
            ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOR()) {
            ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOI()) {
            ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOD()) {
            ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getASRS()) {
            ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getSDL()) {
            ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getVDL()) {
            ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getODL()) {
            ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCDL()) {
            ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
        }
    }

    // add default option "all"
    if (ops.size() == 0) {
        ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
    }

    // String[] tradional_ops = ops.toArray(new String[0]);
    // set system
    setJMutationStructureAndSession(sessionName);
    // MutationSystem.setJMutationStructureAndSession(sessionName);
    MutationSystem.recordInheritanceRelation();
    // generate mutants
    generateMutants(file_list, ops);

    //System.exit(0);
}

From source file:com.p2p.peercds.cli.TorrentMain.java

/**
 * Torrent reader and creator.//from   w  w  w  .  java 2 s.  c o m
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                File[] files = source.listFiles(Constants.hiddenFilesFilter);
                Arrays.sort(files);
                torrent = Torrent.create(source, Arrays.asList(files), announceList, creator);
            } else {
                torrent = Torrent.create(source, announceList, creator);

            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}