Example usage for java.lang String lastIndexOf

List of usage examples for java.lang String lastIndexOf

Introduction

In this page you can find the example usage for java.lang String lastIndexOf.

Prototype

public int lastIndexOf(String str) 

Source Link

Document

Returns the index within this string of the last occurrence of the specified substring.

Usage

From source file:at.treedb.util.SevenZip.java

public static void main(String args[]) throws IOException {
    System.out.println("Extract");
    HashMap<String, byte[]> map = exctact(new File("c:/TreeDBdata/domains/ZooDB.7z"), "info.xml", "classes/");
    for (String s : map.keySet()) {
        if (s.startsWith("classes/")) {
            String className = s.substring("classes/".length(), s.lastIndexOf(".class")).replace("/", ".");
            System.out.println(className);
        }//w  w w .ja  v a 2s.  co  m
    }
}

From source file:com.datazuul.iiif.presentation.api.ManifestGenerator.java

public static void main(String[] args)
        throws ParseException, JsonProcessingException, IOException, URISyntaxException {
    Options options = new Options();
    options.addOption("d", true, "Absolute file path to the directory containing the image files.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("d")) {
        String imageDirectoryPath = cmd.getOptionValue("d");
        Path imageDirectory = Paths.get(imageDirectoryPath);
        final List<Path> files = new ArrayList<>();
        try {//  w  w w.  j  av a  2 s .  c  o m
            Files.walkFileTree(imageDirectory, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (!attrs.isDirectory()) {
                        // TODO there must be a more elegant solution for filtering jpeg files...
                        if (file.getFileName().toString().endsWith("jpg")) {
                            files.add(file);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(files, new Comparator() {
            @Override
            public int compare(Object fileOne, Object fileTwo) {
                String filename1 = ((Path) fileOne).getFileName().toString();
                String filename2 = ((Path) fileTwo).getFileName().toString();

                try {
                    // numerical sorting
                    Integer number1 = Integer.parseInt(filename1.substring(0, filename1.lastIndexOf(".")));
                    Integer number2 = Integer.parseInt(filename2.substring(0, filename2.lastIndexOf(".")));
                    return number1.compareTo(number2);
                } catch (NumberFormatException nfe) {
                    // alpha-numerical sorting
                    return filename1.compareToIgnoreCase(filename2);
                }
            }
        });

        generateManifest(imageDirectory.getFileName().toString(), files);
    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ManifestGenerator", options);
    }
}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/*www .jav  a 2  s .  c o m*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}

From source file:de.dfki.dmas.owls2wsdl.core.OWLS2WSDL.java

public static void main(String[] args) {
    // http://jakarta.apache.org/commons/cli/usage.html
    System.out.println("ARG COUNT: " + args.length);

    OWLS2WSDLSettings.getInstance();/* ww  w. j a  va  2s .  c  om*/

    Options options = new Options();
    Option help = new Option("help", "print help message");
    options.addOption(help);

    // create the parser
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine = null;

    for (int i = 0; i < args.length; i++) {
        System.out.println("ARG: " + args[i].toString());
    }

    if (args.length > 0) {
        if (args[args.length - 1].toString().endsWith(".owl")) {
            // -kbdir d:\tmp\KB http://127.0.0.1/ontology/ActorDefault.owl
            Option test = new Option("test", "parse only, don't save");
            @SuppressWarnings("static-access")
            Option kbdir = OptionBuilder.withArgName("dir").hasArg()
                    .withDescription("knowledgebase directory; necessary").create("kbdir");
            options.addOption(test);
            options.addOption(kbdir);

            try {
                cmdLine = parser.parse(options, args);
                if (cmdLine.hasOption("help")) {
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("owls2wsdl [options] FILE.owl", options);
                    System.exit(0);
                }
            } catch (ParseException exp) {
                // oops, something went wrong
                System.out.println("Error: Parsing failed, reason: " + exp.getMessage());
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl", options, true);
            }

            if (args.length == 1) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl [options] FILE.owl", options);
                System.out.println("Error: Option -kbdir is missing.");
                System.exit(0);
            } else {
                String ontURI = args[args.length - 1].toString();
                String persistentName = "KB_"
                        + ontURI.substring(ontURI.lastIndexOf("/") + 1, ontURI.lastIndexOf(".")) + "-MAP.xml";

                try {
                    if (cmdLine.hasOption("kbdir")) {
                        String kbdirValue = cmdLine.getOptionValue("kbdir");
                        if (new File(kbdirValue).isDirectory()) {
                            DatatypeParser p = new DatatypeParser();
                            p.parse(args[args.length - 1].toString());
                            p.getAbstractDatatypeKBData();
                            if (!cmdLine.hasOption("test")) {
                                System.out.println("AUSGABE: " + kbdirValue + File.separator + persistentName);
                                FileOutputStream ausgabeStream = new FileOutputStream(
                                        kbdirValue + File.separator + persistentName);
                                AbstractDatatypeKB.getInstance().marshallAsXML(ausgabeStream, true); // System.out);
                            }
                        }
                    }
                } catch (java.net.MalformedURLException murle) {
                    System.err.println("MalformedURLException: " + murle.getMessage());
                    System.err.println("Try something like: http://127.0.0.1/ontology/my_ontology.owl");
                } catch (Exception e) {
                    System.err.println("Exception: " + e.toString());
                }
            }
        } else if (args[args.length - 1].toString().endsWith(".xml")) {
            // -owlclass http://127.0.0.1/ontology/Student.owl#HTWStudent
            // -xsd -d 1 -h D:\tmp\KB\KB_Student-MAP.xml
            Option xsd = new Option("xsd", "generate XML Schema");
            Option info = new Option("info", "print datatype information");
            @SuppressWarnings("static-access")
            Option owlclass = OptionBuilder.withArgName("class").hasArg()
                    .withDescription("owl class to translate; necessary").create("owlclass");
            Option keys = new Option("keys", "list all owlclass keys");
            options.addOption(keys);
            options.addOption(owlclass);
            options.addOption(info);
            options.addOption(xsd);
            options.addOption("h", "hierarchy", false, "use hierarchy pattern");
            options.addOption("d", "depth", true, "set recursion depth");
            options.addOption("b", "behavior", true, "set inheritance bevavior");
            options.addOption("p", "primitive", true, "set default primitive type");

            try {
                cmdLine = parser.parse(options, args);
                if (cmdLine.hasOption("help")) {
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("owls2wsdl [options] FILE.xml", options);
                    System.exit(0);
                }
            } catch (ParseException exp) {
                // oops, something went wrong
                System.out.println("Error: Parsing failed, reason: " + exp.getMessage());
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl", options, true);
            }

            if (args.length == 1) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl [options] FILE.xml", options);
                System.exit(0);
            } else if (cmdLine.hasOption("keys")) {
                File f = new File(args[args.length - 1].toString());
                try {
                    AbstractDatatypeMapper.getInstance().loadAbstractDatatypeKB(f);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    System.exit(1);
                }
                AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().printRegisteredDatatypes();
                System.exit(0);
            } else if (!cmdLine.hasOption("owlclass")) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("owls2wsdl [options] FILE.xml", "", options,
                        "Info: owl class not set.\n e.g. -owlclass http://127.0.0.1/ontology/Student.owl#Student");
                System.exit(0);
            } else {
                File f = new File(args[args.length - 1].toString());
                try {
                    AbstractDatatypeMapper.getInstance().loadAbstractDatatypeKB(f);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    System.exit(1);
                }

                String owlclassString = cmdLine.getOptionValue("owlclass");
                if (!AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().containsKey(owlclassString)) {
                    System.err.println("Error: Key " + owlclassString + " not in knowledgebase.");
                    System.exit(1);
                }

                if (cmdLine.hasOption("info")) {
                    AbstractDatatypeKB.getInstance().getAbstractDatatypeKBData().get(owlclassString)
                            .printDatatype();
                }
                if (cmdLine.hasOption("xsd")) {
                    boolean hierachy = false;
                    int depth = 0;
                    String inheritanceBehavior = AbstractDatatype.InheritanceByNone;
                    String defaultPrimitiveType = "http://www.w3.org/2001/XMLSchema#string";

                    if (cmdLine.hasOption("h")) {
                        hierachy = true;
                    }
                    if (cmdLine.hasOption("d")) {
                        depth = Integer.parseInt(cmdLine.getOptionValue("d"));
                    }
                    if (cmdLine.hasOption("b")) {
                        System.out.print("Set inheritance behaviour to: ");
                        if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceByParentsFirstRDFTypeSecond)) {
                            System.out.println(AbstractDatatype.InheritanceByParentsFirstRDFTypeSecond);
                            inheritanceBehavior = AbstractDatatype.InheritanceByNone;
                        } else if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond)) {
                            System.out.println(AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond);
                            inheritanceBehavior = AbstractDatatype.InheritanceByRDFTypeFirstParentsSecond;
                        } else if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceByRDFTypeOnly)) {
                            System.out.println(AbstractDatatype.InheritanceByRDFTypeOnly);
                            inheritanceBehavior = AbstractDatatype.InheritanceByRDFTypeOnly;
                        } else if (cmdLine.getOptionValue("b")
                                .equals(AbstractDatatype.InheritanceBySuperClassOnly)) {
                            System.out.println(AbstractDatatype.InheritanceBySuperClassOnly);
                            inheritanceBehavior = AbstractDatatype.InheritanceBySuperClassOnly;
                        } else {
                            System.out.println(AbstractDatatype.InheritanceByNone);
                            inheritanceBehavior = AbstractDatatype.InheritanceByNone;
                        }
                    }
                    if (cmdLine.hasOption("p")) {
                        defaultPrimitiveType = cmdLine.getOptionValue("p");
                        if (defaultPrimitiveType.split("#")[0].equals("http://www.w3.org/2001/XMLSchema")) {
                            System.err.println("Error: Primitive Type not valid: " + defaultPrimitiveType);
                            System.exit(1);
                        }
                    }
                    XsdSchemaGenerator xsdgen = new XsdSchemaGenerator("SCHEMATYPE", hierachy, depth,
                            inheritanceBehavior, defaultPrimitiveType);

                    try {
                        AbstractDatatypeKB.getInstance().toXSD(owlclassString, xsdgen, System.out);
                    } catch (Exception e) {
                        System.err.println("Error: " + e.getMessage());
                    }
                }

            }
        } else {
            try {
                cmdLine = parser.parse(options, args);
                if (cmdLine.hasOption("help")) {
                    printDefaultHelpMessage();
                }
            } catch (ParseException exp) {
                // oops, something went wrong
                System.out.println("Error: Parsing failed, reason: " + exp.getMessage());
                printDefaultHelpMessage();
            }
        }
    } else {
        OWLS2WSDLGui.createAndShowGUI();
    }

    // for(Iterator it=options.getOptions().iterator(); it.hasNext(); ) {
    // String optString = ((Option)it.next()).getOpt();
    // if(cmdLine.hasOption(optString)) {
    // System.out.println("Option set: "+optString);
    // }
    // }

}

From source file:org.sbs.util.BinaryDateDwonLoader.java

/**
 * @param args/*  w ww .jav  a  2 s .c o m*/
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String img = "http://apollo.s.dpool.sina.com.cn/nd/dataent/moviepic/pics/157/moviepic_8d48be1e004c5b05464a7a427d6722e4.jpg";
    BinaryDateDwonLoader dateDwonLoader = BinaryDateDwonLoader.getInstance();
    PageFetchResult result = dateDwonLoader.fetchHeader(img);
    try {
        OutputStream outputStream = new FileOutputStream(
                new File("d:\\" + img.substring(img.lastIndexOf('/') + 1)));
        result.getEntity().writeTo(outputStream);
        outputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:edu.msu.cme.rdp.kmer.KmerFilter.java

public static void main(String[] args) throws Exception {
    final KmerTrie kmerTrie;
    final SeqReader queryReader;
    final SequenceType querySeqType;
    final File queryFile;
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;
    final boolean alignedSeqs;
    final List<String> refLabels = new ArrayList();
    final int maxThreads;

    try {// w w  w .jav a2s.  c  om
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 3) {
            throw new Exception("Unexpected number of arguments");
        }

        if (cmdLine.hasOption("out")) {
            out = new KmerStartsWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new KmerStartsWriter(System.out);
        }

        if (cmdLine.hasOption("aligned")) {
            alignedSeqs = true;
        } else {
            alignedSeqs = false;
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
        } else {
            maxThreads = Runtime.getRuntime().availableProcessors();
        }

        queryFile = new File(args[1]);
        wordSize = Integer.valueOf(args[0]);
        SequenceType refSeqType = null;

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(queryFile);

        if (querySeqType == SequenceType.Protein) {
            throw new Exception("Expected nucl query sequences");
        }

        refSeqType = SeqUtils
                .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2]));

        translQuery = refSeqType == SequenceType.Protein;

        if (translQuery && wordSize % 3 != 0) {
            throw new Exception("Word size must be a multiple of 3 for nucl ref seqs");
        }

        int trieWordSize;
        if (translQuery) {
            trieWordSize = wordSize / 3;
        } else {
            trieWordSize = wordSize;
        }
        kmerTrie = new KmerTrie(trieWordSize, translQuery);

        for (int index = 2; index < args.length; index++) {
            String refName;
            String refFileName = args[index];
            if (refFileName.contains("=")) {
                String[] lexemes = refFileName.split("=");
                refName = lexemes[0];
                refFileName = lexemes[1];
            } else {
                String tmpName = new File(refFileName).getName();
                if (tmpName.contains(".")) {
                    refName = tmpName.substring(0, tmpName.lastIndexOf("."));
                } else {
                    refName = tmpName;
                }
            }

            File refFile = new File(refFileName);

            if (refSeqType != SeqUtils.guessSequenceType(refFile)) {
                throw new Exception(
                        "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                                + " sequences but expected " + refSeqType + " sequences");
            }

            SequenceReader seqReader = new SequenceReader(refFile);
            Sequence seq;

            while ((seq = seqReader.readNextSequence()) != null) {
                if (seq.getSeqName().startsWith("#")) {
                    continue;
                }
                if (alignedSeqs) {
                    kmerTrie.addModelSequence(seq, refLabels.size());
                } else {
                    kmerTrie.addSequence(seq, refLabels.size());
                }
            }
            seqReader.close();

            refLabels.add(refName);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("KmerSearch <word_size> <query_file> [name=]<ref_file> ...", options);
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(1);
        throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables
    }

    long startTime = System.currentTimeMillis();
    long seqCount = 0;
    final int maxTasks = 25000;

    /*
     * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else {
     */

    //}

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  Number of threads:       " + maxThreads);
    System.err.println("*  References:              " + refLabels);
    System.err.println("*  Reads file:              " + queryFile);
    System.err.println("*  Kmer length:             " + kmerTrie.getWordSize());

    final AtomicInteger processed = new AtomicInteger();
    final AtomicInteger outstandingTasks = new AtomicInteger();

    ExecutorService service = Executors.newFixedThreadPool(maxThreads);

    Sequence querySeq;

    while ((querySeq = queryReader.readNextSequence()) != null) {
        seqCount++;

        String seqString = querySeq.getSeqString();

        if (seqString.length() < 3) {
            System.err.println("Sequence " + querySeq.getSeqName() + "'s length is less than 3");
            continue;
        }

        final Sequence threadSeq = querySeq;

        Runnable r = new Runnable() {

            public void run() {
                try {
                    processSeq(threadSeq, refLabels, kmerTrie, out, wordSize, translQuery, translTable, false);
                    processSeq(threadSeq, refLabels, kmerTrie, out, wordSize, translQuery, translTable, true);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                processed.incrementAndGet();
                outstandingTasks.decrementAndGet();
            }
        };

        outstandingTasks.incrementAndGet();
        service.submit(r);

        while (outstandingTasks.get() >= maxTasks)
            ;

        if ((processed.get() + 1) % 1000000 == 0) {
            System.err.println("Processed " + processed + " sequences in "
                    + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    System.err.println("Finished Processed " + processed + " sequences in "
            + (System.currentTimeMillis() - startTime) + " ms");

    out.close();
}

From source file:edu.msu.cme.rdp.kmer.cli.FastKmerFilter.java

public static void main(String[] args) throws Exception {
    final KmerSet<Set<RefKmer>> kmerSet;
    final SeqReader queryReader;
    final SequenceType querySeqType;
    final File queryFile;
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;
    final boolean alignedSeqs;
    final List<String> refLabels = new ArrayList();
    final int maxThreads;
    final int trieWordSize;

    try {//w w w  . j  av  a2s.  c o  m
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 3) {
            throw new Exception("Unexpected number of arguments");
        }

        if (cmdLine.hasOption("out")) {
            out = new KmerStartsWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new KmerStartsWriter(System.out);
        }

        if (cmdLine.hasOption("aligned")) {
            alignedSeqs = true;
        } else {
            alignedSeqs = false;
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
        } else {
            maxThreads = Runtime.getRuntime().availableProcessors();
        }

        queryFile = new File(args[1]);
        wordSize = Integer.valueOf(args[0]);
        SequenceType refSeqType = null;

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(queryFile);

        if (querySeqType == SequenceType.Protein) {
            throw new Exception("Expected nucl query sequences");
        }

        refSeqType = SeqUtils
                .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2]));

        translQuery = refSeqType == SequenceType.Protein;

        if (translQuery && wordSize % 3 != 0) {
            throw new Exception("Word size must be a multiple of 3 for nucl ref seqs");
        }

        if (translQuery) {
            trieWordSize = wordSize / 3;
        } else {
            trieWordSize = wordSize;
        }
        kmerSet = new KmerSet<Set<RefKmer>>();//new KmerTrie(trieWordSize, translQuery);

        for (int index = 2; index < args.length; index++) {
            String refName;
            String refFileName = args[index];
            if (refFileName.contains("=")) {
                String[] lexemes = refFileName.split("=");
                refName = lexemes[0];
                refFileName = lexemes[1];
            } else {
                String tmpName = new File(refFileName).getName();
                if (tmpName.contains(".")) {
                    refName = tmpName.substring(0, tmpName.lastIndexOf("."));
                } else {
                    refName = tmpName;
                }
            }

            File refFile = new File(refFileName);

            if (refSeqType != SeqUtils.guessSequenceType(refFile)) {
                throw new Exception(
                        "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                                + " sequences but expected " + refSeqType + " sequences");
            }

            SequenceReader seqReader = new SequenceReader(refFile);
            Sequence seq;

            while ((seq = seqReader.readNextSequence()) != null) {
                if (seq.getSeqName().startsWith("#")) {
                    continue;
                }

                KmerGenerator kmers;
                try {
                    if (translQuery) { //protein ref
                        kmers = new ProtKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    } else {
                        kmers = new NuclKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    }
                    while (kmers.hasNext()) {
                        Kmer temp = kmers.next();
                        long[] next = temp.getLongKmers();
                        Set<RefKmer> refKmers = kmerSet.get(next);
                        if (refKmers == null) {
                            refKmers = new HashSet();
                            kmerSet.add(next, refKmers);
                        }

                        RefKmer kmerRef = new RefKmer();
                        kmerRef.modelPos = kmers.getPosition();
                        kmerRef.refFileIndex = refLabels.size();
                        kmerRef.refSeqid = seq.getSeqName();
                        refKmers.add(kmerRef);
                    }
                } catch (IllegalArgumentException ex) {
                    //System.err.println(seq.getSeqName()+ " " + ex.getMessage());
                }
            }
            seqReader.close();

            refLabels.add(refName);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "KmerSearch <kmerSize> <query_file> [name=]<ref_file> ...\nkmerSize should be multiple of 3, (recommend 45, minimum 30, maximum 63) ",
                options);
        e.printStackTrace();
        System.exit(1);
        throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables
    }

    long startTime = System.currentTimeMillis();
    long seqCount = 0;
    final int maxTasks = 25000;

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  Number of threads:       " + maxThreads);
    System.err.println("*  References:              " + refLabels);
    System.err.println("*  Reads file:              " + queryFile);
    System.err.println("*  Kmer length:             " + trieWordSize);
    System.err.println("*  Kmer Refset Size:        " + kmerSet.size());

    final AtomicInteger processed = new AtomicInteger();
    final AtomicInteger outstandingTasks = new AtomicInteger();

    ExecutorService service = Executors.newFixedThreadPool(maxThreads);

    Sequence querySeq;

    while ((querySeq = queryReader.readNextSequence()) != null) {
        seqCount++;

        String seqString = querySeq.getSeqString();

        if ((!translQuery && seqString.length() < wordSize)
                || (translQuery && seqString.length() < wordSize + 2)) {
            //System.err.println(querySeq.getSeqName() + "\t" + seqString.length());
            continue;
        }

        final Sequence threadSeq = querySeq;

        Runnable r = new Runnable() {

            public void run() {
                try {
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, false);
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, true);

                    processed.incrementAndGet();
                    outstandingTasks.decrementAndGet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        outstandingTasks.incrementAndGet();
        service.submit(r);

        while (outstandingTasks.get() >= maxTasks)
            ;

        if ((processed.get() + 1) % 1000000 == 0) {
            System.err.println("Processed " + processed + " sequences in "
                    + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    System.err.println("Finished Processed " + processed + " sequences in "
            + (System.currentTimeMillis() - startTime) + " ms");

    out.close();
}

From source file:edu.duke.igsp.gkde.Main.java

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

    Options opts = new Options();
    opts.addOption("s", true, "wiggle track step (default=1)");
    opts.addOption("l", true, "feature length (default=600)");
    opts.addOption("f", true, "fragment size (default=estimated from data)");
    //    opts.addOption("b", true, "bandwidth (default=200)");
    //    opts.addOption("w", true, "window (default=3800");
    opts.addOption("wg", true, "wg threshold set (defualt = calculated)");
    opts.addOption("c", true, "genomic total read weight (defualt = calculated)");
    opts.addOption("h", false, "print usage");
    opts.addOption(OptionBuilder.withArgName("input dir").hasArg()
            .withDescription("input directory (default=current directory)").isRequired(false).create("d"));
    opts.addOption(OptionBuilder.withArgName("output dir").hasArg()
            .withDescription("output directory (default=current directory)").isRequired(false).create("o"));
    opts.addOption(OptionBuilder.withArgName("background dir").hasArg()
            .withDescription("background directory (default=none)").isRequired(false).create("b"));
    opts.addOption(OptionBuilder.withArgName("ploidy dir").hasArg()
            .withDescription("ploidy/input directory (default=none)").isRequired(false).create("p"));
    opts.addOption(OptionBuilder.withArgName("wig | bed | npf").hasArg()
            .withDescription("output format (default wig)").isRequired(false).create("of"));
    opts.addOption(OptionBuilder.withArgName("dnase | chip | faire | atac").hasArg()
            .withDescription("input data").isRequired(true).create("in"));
    opts.addOption(OptionBuilder.withArgName("weight clip").hasArg()
            .withDescription("weight clip value (default none)").isRequired(false).create("wc"));
    opts.addOption("t", true, "threshold (standard deviations) (default=4.0)");
    //    opts.addOption("r", true, "background ratio (default=2.0)");
    opts.addOption("v", false, "verbose output");

    CommandLineParser parser = new GnuParser();
    int fragment_size = -1;
    int fragment_offset = 0;
    long featureLength = 600l;
    //    float thresh = 2;
    float threshold = KDEChromosome.Settings.DEFAULT_THRESHOLD;
    int step = 1;
    boolean showHelp = false;
    boolean verbose = false;
    String inputDirectory = null;
    String backgroundDirectory = null;
    String ploidyDirectory = null;
    String[] files = null;//from   w w w .  ja v  a 2  s . c  om
    String[] bgfiles = {};
    String[] ipfiles = {};
    String outputFormat = "wig";
    String inputDataType = "dnase";
    File outputDirectory = new File(System.getProperty("user.dir"));

    long bandwidth = 0l;
    long window = 0l;
    double ncuts = 0.0d;
    float temp_threshold = 0f;
    int weight_clip = 0;

    System.out.println("F-Seq Version 1.85");

    try {
        CommandLine cmd = parser.parse(opts, argv);
        showHelp = (cmd.hasOption("h"));
        verbose = (cmd.hasOption("v"));
        if (cmd.hasOption("s"))
            step = Integer.parseInt(cmd.getOptionValue("s"));
        if (cmd.hasOption("f"))
            fragment_size = Integer.parseInt(cmd.getOptionValue("f"));
        if (cmd.hasOption("d")) //input directory
            inputDirectory = cmd.getOptionValue("d");
        if (cmd.hasOption("b")) //background directory
            backgroundDirectory = cmd.getOptionValue("b");
        if (cmd.hasOption("p")) //ploidy|input directory
            ploidyDirectory = cmd.getOptionValue("p");
        if (cmd.hasOption("l")) // bandwidth
            featureLength = Long.parseLong(cmd.getOptionValue("l"));
        if (cmd.hasOption("of")) { // output format
            outputFormat = cmd.getOptionValue("of");
            if (!outputFormat.equals("wig") && !outputFormat.equals("bed") && !outputFormat.equals("npf")) {
                System.out.println("Parameter error: output format must be 'wig' or 'bed'.");
                showHelp = true;
            }
        }
        if (cmd.hasOption("in")) { // input data type
            inputDataType = cmd.getOptionValue("in");
            if (!inputDataType.equals("dnase") && !inputDataType.equals("chip")
                    && !inputDataType.equals("faire") && !inputDataType.equals("atac")) {
                System.out.println(
                        "Parameter error: input data type must be 'dnase', 'chip', 'faire', or 'atac'.");
                showHelp = true;
            }
        }
        if (cmd.hasOption("wc")) { // weight clip
            weight_clip = Integer.parseInt(cmd.getOptionValue("wc"));
        }
        if (cmd.hasOption("t")) { // threshold (standard deviations)
            threshold = Float.parseFloat(cmd.getOptionValue("t"));
        }
        if (cmd.hasOption("o")) { // output directory
            String out = cmd.getOptionValue("o");
            outputDirectory = new File(out);
            if (!outputDirectory.exists() && !outputDirectory.isDirectory()) {
                System.out.println("Output directory '" + out + "' is not a valid directory.");
                showHelp = true;
            }
        }

        if (cmd.hasOption("wg"))
            temp_threshold = Float.parseFloat(cmd.getOptionValue("wg"));
        if (cmd.hasOption("c"))
            ncuts = Double.parseDouble(cmd.getOptionValue("c"));

        // TESTING ONLY
        //   if(cmd.hasOption("w")) // window
        //     window = Long.parseLong(cmd.getOptionValue("w"));
        //if(cmd.hasOption("b")) // window
        //  bandwidth = Long.parseLong(cmd.getOptionValue("b"));

        files = cmd.getArgs(); // input files
        //bgfiles = cmd.getArgs(); // background files
    } catch (Exception e) {
        System.out.println("Error parsing arguments: " + e.getMessage());
        e.printStackTrace();
        showHelp = true;
    }

    if (showHelp || (inputDirectory == null && files.length == 0)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fseq [options]... [file(s)]...", opts);
        System.exit(1);
    }

    File[] pfiles = getFiles(inputDirectory, files);
    File[] background_files = getFiles(backgroundDirectory, bgfiles);
    File[] ploidy_files = getFiles(ploidyDirectory, ipfiles);

    KDEChromosome[] chrs = null;
    // assume all files are of the same type, if not we'll get parsing errors
    String path = pfiles[0].getPath();
    String extension = path.substring(path.lastIndexOf('.')).toLowerCase();
    System.out.println("Path: " + path + ", extension: " + extension);
    if (extension.equals(".bed")) {
        System.out.println("Parsing BED file.");
        chrs = BedReader.read(pfiles);
    } else if (extension.equals(".sam") || extension.equals(".bam")) {
        System.out.println("Parsing SAM/BAM file.");
        chrs = SamReader.read(pfiles, weight_clip);
    }
    //KDEChromosome[] input = BedReader.read(ifiles);

    //compute fragment offset
    if (fragment_size == -1) {
        fragment_size = wgShiftCalc(chrs);
    }
    fragment_offset = (int) (fragment_size / 2);

    if (ncuts == 0.0d) {
        for (int i = 0; i < chrs.length; ++i) {
            // computes the total read weight of all cuts on a chromosome
            ncuts += chrs[i].getTotalWeight();
        }
    }

    KDEChromosome.Settings settings = null;
    if (bandwidth > 0 || window > 0) {
        settings = new KDEChromosome.Settings(bandwidth, window, threshold, fragment_offset, ncuts,
                inputDataType);
    } else {
        settings = new KDEChromosome.Settings(featureLength, threshold, fragment_offset, ncuts, inputDataType);
    }

    float wg_threshold = wgThreshold(settings, chrs);
    if (temp_threshold != 0f) {
        wg_threshold = temp_threshold;
    }
    //KDEChromosome.Settings bg_settings = null;
    //bg_settings = new KDEChromosome.Settings(featureLength*2, threshold, fragment_offset);

    //int background_size = 0;
    //int input_size = 0;
    //float bg_ratio = 0;
    //float sd = 0;

    if (verbose) {
        System.out.println("Settings: ");
        System.out.println("\twindow=" + (settings.window * 2));
        System.out.println("\tbandwidth=" + (settings.bandwidth));
        //System.out.println("\tfragment offset=" + (settings.offset));
        System.out.println("\tthreshold = " + wg_threshold);
        System.out.println("\test. fragment size = " + fragment_size);
        System.out.println("\tsequence length = " + chrs[0].getSequenceLength());
    }

    //    if(backgroundDirectory != null) {
    //       for(int i = 0; i < input.length; ++i) {
    //          background_size += input[i].getLength();
    //       }
    //       for(int i = 0; i < chrs.length; ++i) {
    //          input_size += chrs[i].getLength();
    //       }
    //       bg_ratio = (float)input_size/(float)background_size;
    //       sd = computeSD(bg_settings, input);
    //       //System.out.println("Sample Ratio: " + bg_ratio);
    //       //System.out.println("Input Size: " + input_size);
    //       //System.out.println("Background Size: " + background_size);
    //       //System.out.println("Input standard deviation: " + (settings.threshold * (float)Math.sqrt((double)bg_ratio * (double)sd * (double)sd)));
    //       //System.out.println("Data standard deviation: " + settings.threshold * computeSD(settings, chrs));
    //    }

    for (int i = 0; i < chrs.length; ++i) {
        if (chrs[i].getFirstPos() == chrs[i].getLastPos()) {
            System.out.println("Warning: " + chrs[i].getChromosome() + " has size zero.  Skipping.");
            continue;
        }
        File ofile = Util.makeUniqueFileWithExtension(outputDirectory, chrs[i].getChromosome(), outputFormat);

        DensityWriter dw = null;
        if (outputFormat.equals("wig")) {
            dw = new WiggleDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
        } else {
            if (outputFormat.equals("npf")) {
                dw = new NpfDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
            } else {
                dw = new BedDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
            }
        }

        //Function takes all? or new function for each?
        //      if(backgroundDirectory != null) {
        //         boolean hit = false;
        //         for(int j = 0; j < background_files.length; ++j) {
        //            if(background_files[j].getName().equals(chrs[i].getChromosome() + ".bff")) {
        //               System.out.println("Running background on Chromosome " + chrs[i].getChromosome());
        //               chrs[i].runBG(settings, dw, verbose, wg_threshold, background_files[j]);
        //               hit = true;
        //            }
        //         }
        //         if(!hit)
        //            System.out.println("No background for Chromosome " + chrs[i].getChromosome());
        //      } else {
        //         if(ploidyDirectory !=)
        //         chrs[i].run(settings, dw, verbose, wg_threshold);
        //      }
        chrs[i].run(settings, dw, verbose, wg_threshold, background_files, ploidy_files);
        dw.close();
    }

    //kde.showGraph();
}

From source file:ffx.xray.TimerTest.java

public static void main(String args[]) {
    // Parameters collection from original Timer script
    String pdbname = System.getProperty("pdbFile", "1N7S.pdb");
    String mtzname = System.getProperty("mtzFile", null);
    String cifname = System.getProperty("cifFile", null);
    final boolean ciOnly = false;
    final String info = "SNARE complex";
    final double r = 19.412671496011;
    final double rfree = 21.555930987573;
    final double sigmaA = 0.9336853524690557;
    final double sigmaW = 0.13192537249786418;

    boolean ci = System.getProperty("ffx.ci", "false").equalsIgnoreCase("true");
    if (!ci && ciOnly) {
        crystalStats = null;/* ww w . java2s .  c  o  m*/
        return;
    }

    int index = pdbname.lastIndexOf(".");
    String name = pdbname.substring(0, index);

    // load the structure
    MolecularAssembly molecularAssembly;
    File structure, mtzFile, cifFile;
    structure = new File(pdbname);
    PotentialsFileOpener opener = new PotentialsFileOpener(structure);
    opener.run();
    molecularAssembly = opener.getAssembly();
    mtzFile = new File(mtzname);
    cifFile = new File(cifname);

    // load any properties associated with it
    CompositeConfiguration properties = Keyword.loadProperties(structure);

    // read in Fo/sigFo/FreeR
    MTZFilter mtzFilter = new MTZFilter();
    CIFFilter cifFilter = new CIFFilter();
    Crystal crystal = Crystal.checkProperties(properties);
    Resolution resolution = Resolution.checkProperties(properties);
    if (crystal == null || resolution == null) {
        if (mtzname != null) {
            reflectionList = mtzFilter.getReflectionList(mtzFile);
        } else {
            reflectionList = cifFilter.getReflectionList(cifFile);
        }
    } else {
        reflectionList = new ReflectionList(crystal, resolution);
    }

    refinementData = new DiffractionRefinementData(properties, reflectionList);
    if (mtzname != null) {
        //            assertTrue(info + " mtz file should be read in without errors",
        //                    mtzFilter.readFile(mtzFile, reflectionList, refinementData,
        //                            properties));
    } else {
        //            assertTrue(info + " cif file should be read in without errors",
        //                    cifFilter.readFile(cifFile, reflectionList, refinementData,
        //                            properties));
    }

    ForceFieldFilter forceFieldFilter = new ForceFieldFilter(properties);
    ForceField forceField = forceFieldFilter.parse();

    // associate molecular assembly with the structure, set up forcefield
    molecularAssembly.setForceField(forceField);
    PDBFilter pdbFile = new PDBFilter(structure, molecularAssembly, forceField, properties);
    pdbFile.readFile();
    pdbFile.applyAtomProperties();
    molecularAssembly.finalize(true, forceField);
    ForceFieldEnergy energy = new ForceFieldEnergy(molecularAssembly, pdbFile.getCoordRestraints());

    List<Atom> atomList = molecularAssembly.getAtomList();
    Atom atomArray[] = atomList.toArray(new Atom[atomList.size()]);

    // set up FFT and run it
    parallelTeam = new ParallelTeam();
    CrystalReciprocalSpace crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam,
            parallelTeam, false);
    crs.computeDensity(refinementData.fc);
    refinementData.setCrystalReciprocalSpace_fc(crs);
    crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam, parallelTeam, true);
    crs.computeDensity(refinementData.fs);
    refinementData.setCrystalReciprocalSpace_fs(crs);

    ScaleBulkMinimize scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, crs,
            parallelTeam);
    scaleBulkMinimize.minimize(6, 1.0e-4);

    SigmaAMinimize sigmaAMinimize = new SigmaAMinimize(reflectionList, refinementData, parallelTeam);
    sigmaAMinimize.minimize(7, 2.0e-2);

    SplineMinimize splineMinimize = new SplineMinimize(reflectionList, refinementData, refinementData.spline,
            SplineEnergy.Type.FOFC);
    splineMinimize.minimize(7, 1e-5);

    crystalStats = new CrystalStats(reflectionList, refinementData);

    scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, refinementData.crs_fs,
            parallelTeam);
    ScaleBulkEnergy scaleBulkEnergy = scaleBulkMinimize.getScaleBulkEnergy();
    int n = scaleBulkMinimize.getNumberOfVariables();
    double x[] = new double[n];
    double g[] = new double[n];
    scaleBulkMinimize.getCoordinates(x);
    scaleBulkEnergy.energyAndGradient(x, g);

    double delta = 1.0e-4;
    double tolerance = 1.0e-4;

    logger.info(String.format("SCATTER TEST"));
    for (int i = 0; i < 30; i++) {
        long time = -System.nanoTime();
        scaleBulkEnergy.energyAndGradient(x, g);
        time += System.nanoTime();
        logger.info(String.format(" Time %12.8f", time * 1.0e-9));
    }
}

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;/*from w  w w  .  ja va  2 s.c  o m*/
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}