Example usage for java.util StringTokenizer nextToken

List of usage examples for java.util StringTokenizer nextToken

Introduction

In this page you can find the example usage for java.util StringTokenizer nextToken.

Prototype

public String nextToken() 

Source Link

Document

Returns the next token from this string tokenizer.

Usage

From source file:correospingtelnet.Telnet.java

public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    String remoteip = "64.62.142.154";

    int remoteport = 23;

    try {// w w  w  . j av a  2  s. c o  m
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new Telnet());
            tc.registerNotifHandler(new Telnet());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");
            System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        final String line = new String(buff, 0, ret_read); // deliberate use of default charset
                        if (line.startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if (line.startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if (line.startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if (line.startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if (line.startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if (line.startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else if (line.matches("^\\^[A-Z^]\\r?\\n?$")) {
                            byte toSend = buff[1];
                            if (toSend == '^') {
                                outstr.write(toSend);
                            } else {
                                outstr.write(toSend - 'A' + 1);
                            }
                            outstr.flush();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.bitsofproof.example.Simple.java

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());

    final CommandLineParser parser = new GnuParser();
    final Options gnuOptions = new Options();
    gnuOptions.addOption("h", "help", false, "I can't help you yet");
    gnuOptions.addOption("s", "server", true, "Server URL");
    gnuOptions.addOption("u", "user", true, "User");
    gnuOptions.addOption("p", "password", true, "Password");

    System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt.");
    CommandLine cl = null;//from  w w w.  ja  va2 s .c om
    String url = null;
    String user = null;
    String password = null;
    try {
        cl = parser.parse(gnuOptions, args);
        url = cl.getOptionValue('s');
        user = cl.getOptionValue('u');
        password = cl.getOptionValue('p');
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
        System.exit(1);
    }
    if (url == null || user == null || password == null) {
        System.err.println("Need -s server -u user -p password");
        System.exit(1);
    }

    BCSAPI api = getServer(url, user, password);
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        long start = System.currentTimeMillis();
        api.ping(start);
        System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms");
        api.addAlertListener(new AlertListener() {
            @Override
            public void alert(String s, int severity) {
                System.err.println("ALERT: " + s);
            }
        });
        System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server");
        ConfirmationManager confirmationManager = new ConfirmationManager();
        confirmationManager.init(api, 144);
        System.out.printf("Please enter wallet name: ");
        String wallet = input.readLine();
        SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet");
        TransactionFactory am = null;
        if (!w.exists()) {
            System.out.printf("Enter passphrase: ");
            String passphrase = input.readLine();
            System.out.printf("Enter master (empty for new): ");
            String master = input.readLine();
            if (master.equals("")) {
                w.init(passphrase);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
            } else {
                StringTokenizer tokenizer = new StringTokenizer(master, "@");
                String key = tokenizer.nextToken();
                long since = 0;
                if (tokenizer.hasMoreElements()) {
                    since = Long.parseLong(tokenizer.nextToken()) * 1000;
                }
                w.init(passphrase, ExtendedKey.parse(key), true, since);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
                w.sync(api);
            }
        } else {
            w = SimpleFileWallet.read(wallet + ".wallet");
            w.sync(api);
            List<String> names = w.getAccountNames();
            System.out.println("Accounts:");
            System.out.println("---------");
            String first = null;
            for (String name : names) {
                System.out.println(name);
                if (first == null) {
                    first = name;
                }
            }
            System.out.println("---------");
            am = w.getAccountManager(first);
            System.out.println("Using account " + first);
        }
        confirmationManager.addAccount(am);
        api.registerTransactionListener(am);

        while (true) {
            printMenu();
            String answer = input.readLine();
            System.out.printf("\n");
            if (answer.equals("1")) {
                System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n");
                System.out.printf("     confirmed: " + printBit(am.getConfirmed()) + "\n");
                System.out.printf("    receiveing: " + printBit(am.getReceiving()) + "\n");
                System.out.printf("        change: " + printBit(am.getChange()) + "\n");
                System.out.printf("(      sending: " + printBit(am.getSending()) + ")\n");
            } else if (answer.equals("2")) {
                for (Address a : am.getAddresses()) {
                    System.out.printf(a + "\n");
                }
            } else if (answer.equals("3")) {
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
            } else if (answer.equals("4")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
                w.lock();
            } else if (answer.equals("5")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.printf("Number of recipients");
                Integer nr = Integer.valueOf(input.readLine());
                Transaction spend;
                if (nr.intValue() == 1) {
                    System.out.printf("Receiver address: ");
                    String address = input.readLine();
                    System.out.printf("amount (Bit): ");
                    long amount = parseBit(input.readLine());
                    spend = am.pay(Address.fromSatoshiStyle(address), amount);
                    System.out.println("About to send " + printBit(amount) + " to " + address);
                } else {
                    List<Address> addresses = new ArrayList<>();
                    List<Long> amounts = new ArrayList<>();
                    long total = 0;
                    for (int i = 0; i < nr; ++i) {
                        System.out.printf("Receiver address: ");
                        String address = input.readLine();
                        addresses.add(Address.fromSatoshiStyle(address));
                        System.out.printf("amount (Bit): ");
                        long amount = parseBit(input.readLine());
                        amounts.add(amount);
                        total += amount;
                    }
                    spend = am.pay(addresses, amounts);
                    System.out.println("About to send " + printBit(total));
                }
                System.out.println("inputs");
                for (TransactionInput in : spend.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : spend.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                w.lock();
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(spend);
                    System.out.printf("Sent transaction: " + spend.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else if (answer.equals("6")) {
                System.out.printf("Address: ");
                Set<Address> match = new HashSet<Address>();
                match.add(Address.fromSatoshiStyle(input.readLine()));
                api.scanTransactionsForAddresses(match, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("7")) {
                System.out.printf("Public key: ");
                ExtendedKey ek = ExtendedKey.parse(input.readLine());
                api.scanTransactions(ek, 0, 10, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("a")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                am = w.getAccountManager(account);
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("c")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                am = w.createAccountManager(account);
                System.out.println("using account: " + account);
                w.lock();
                w.persist();
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("m")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.println(w.getMaster().serialize(api.isProduction()));
                System.out.println(w.getMaster().getReadOnly().serialize(true));
                w.lock();
            } else if (answer.equals("s")) {
                System.out.printf("Enter private key: ");
                String key = input.readLine();
                ECKeyPair k = ECKeyPair.parseWIF(key);
                KeyListAccountManager alm = new KeyListAccountManager();
                alm.addKey(k);
                alm.syncHistory(api);
                Address a = am.getNextReceiverAddress();
                Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee);
                System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a);
                System.out.println("inputs");
                for (TransactionInput in : t.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : t.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(t);
                    System.out.printf("Sent transaction: " + t.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else {
                System.exit(0);
            }
        }
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:IndexService.Indexer.java

public static void main(String[] args) throws IOException {
    System.out.println("input cmd:   indexdir  idx  type  startvalue  endvalue");
    String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
    StringTokenizer st = new StringTokenizer(str);
    String indexdir = st.nextToken();
    int idx = Integer.parseInt(st.nextToken());
    String type = st.nextToken();
    String startvalue = st.nextToken();
    String endvalue = null;//w w w.  java2s. c o m
    if (st.hasMoreTokens())
        endvalue = st.nextToken();
    else
        endvalue = startvalue;
    ArrayList<IRecord.IFValue> values = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values.add(new IRecord.IFValue(Byte.parseByte(startvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values.add(new IRecord.IFValue(Short.parseShort(startvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values.add(new IRecord.IFValue(Integer.parseInt(startvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values.add(new IRecord.IFValue(Long.parseLong(startvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values.add(new IRecord.IFValue(Float.parseFloat(startvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values.add(new IRecord.IFValue(Double.parseDouble(startvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values.add(new IRecord.IFValue(startvalue, idx));
    ArrayList<IRecord.IFValue> values1 = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values1.add(new IRecord.IFValue(Byte.parseByte(endvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values1.add(new IRecord.IFValue(Short.parseShort(endvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values1.add(new IRecord.IFValue(Integer.parseInt(endvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values1.add(new IRecord.IFValue(Long.parseLong(endvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values1.add(new IRecord.IFValue(Float.parseFloat(endvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values1.add(new IRecord.IFValue(Double.parseDouble(endvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values1.add(new IRecord.IFValue(endvalue, idx));
    Indexer indexer = new Indexer();
    List<IRecord> recs = indexer.getRange(indexdir, null, values, values1, 100, null, -1);
    for (IRecord rec : recs) {
        rec.show();
    }

}

From source file:hepple.postag.POSTagger.java

/**
 * Main method. Runs the tagger using the arguments to find the resources
 * to be used for initialisation and the input file.
 *///from www  .jav a  2s  . co m
public static void main(String[] args) {
    if (args.length == 0)
        help();
    try {
        LongOpt[] options = new LongOpt[] { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
                new LongOpt("lexicon", LongOpt.NO_ARGUMENT, null, 'l'),
                new LongOpt("rules", LongOpt.NO_ARGUMENT, null, 'r') };
        Getopt getopt = new Getopt("HepTag", args, "hl:r:", options);
        String lexiconUrlString = null;
        String rulesUrlString = null;
        int opt;
        while ((opt = getopt.getopt()) != -1) {
            switch (opt) {
            // -h
            case 'h': {
                help();
                System.exit(0);
                break;
            }
            // -l new lexicon
            case 'l': {
                lexiconUrlString = getopt.getOptarg();
                break;
            }
            // -l new lexicon
            case 'r': {
                rulesUrlString = getopt.getOptarg();
                break;
            }
            default: {
                System.err.println("Invalid option " + args[getopt.getOptind() - 1] + "!");
                System.exit(1);
            }
            }//switch(opt)
        } //while( (opt = g.getopt()) != -1 )
        String[] fileNames = new String[args.length - getopt.getOptind()];
        for (int i = getopt.getOptind(); i < args.length; i++) {
            fileNames[i - getopt.getOptind()] = args[i];
        }

        URL lexiconURL = (lexiconUrlString == null)
                ? POSTagger.class.getResource("/hepple/resources/sample_lexicon")
                : new File(lexiconUrlString).toURI().toURL();

        URL rulesURL = (rulesUrlString == null)
                ? POSTagger.class.getResource("/hepple/resources/sample_ruleset.big")
                : new File(rulesUrlString).toURI().toURL();

        POSTagger tagger = new POSTagger(lexiconURL, rulesURL);

        for (int i = 0; i < fileNames.length; i++) {
            String file = fileNames[i];
            BufferedReader reader = null;

            try {
                reader = new BufferedReader(new FileReader(file));

                String line = reader.readLine();

                while (line != null) {
                    StringTokenizer tokens = new StringTokenizer(line);
                    List<String> sentence = new ArrayList<String>();
                    while (tokens.hasMoreTokens())
                        sentence.add(tokens.nextToken());
                    List<List<String>> sentences = new ArrayList<List<String>>();
                    sentences.add(sentence);
                    List<List<String[]>> result = tagger.runTagger(sentences);

                    Iterator<List<String[]>> iter = result.iterator();
                    while (iter.hasNext()) {
                        List<String[]> sentenceFromTagger = iter.next();
                        Iterator<String[]> sentIter = sentenceFromTagger.iterator();
                        while (sentIter.hasNext()) {
                            String[] tag = sentIter.next();
                            System.out.print(tag[0] + "/" + tag[1]);
                            if (sentIter.hasNext())
                                System.out.print(" ");
                            else
                                System.out.println();
                        } //while(sentIter.hasNext())
                    } //while(iter.hasNext())
                    line = reader.readLine();
                } //while(line != null)
            } finally {
                IOUtils.closeQuietly(reader);
            }
            //
            //
            //
            //        List result = tagger.runTagger(readInput(file));
            //        Iterator iter = result.iterator();
            //        while(iter.hasNext()){
            //          List sentence = (List)iter.next();
            //          Iterator sentIter = sentence.iterator();
            //          while(sentIter.hasNext()){
            //            String[] tag = (String[])sentIter.next();
            //            System.out.print(tag[0] + "/" + tag[1]);
            //            if(sentIter.hasNext()) System.out.print(" ");
            //            else System.out.println();
            //          }//while(sentIter.hasNext())
            //        }//while(iter.hasNext())
        } //for(int i = 0; i < fileNames.length; i++)
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sun.faces.generate.HtmlComponentGenerator.java

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

    try {//from  ww  w .ja  va  2s  .c  o m

        // Perform setup operations
        if (log.isDebugEnabled()) {
            log.debug("Processing command line options");
        }
        Map options = options(args);
        String dtd = (String) options.get("--dtd");
        if (log.isDebugEnabled()) {
            log.debug("Configuring digester instance with public identifiers and DTD '" + dtd + "'");
        }
        StringTokenizer st = new StringTokenizer(dtd, "|");
        int arrayLen = st.countTokens();
        if (arrayLen == 0) {
            // PENDING I18n
            throw new Exception("No DTDs specified");
        }
        String[] dtds = new String[arrayLen];
        int i = 0;
        while (st.hasMoreTokens()) {
            dtds[i] = st.nextToken();
            i++;
        }

        copyright((String) options.get("--copyright"));
        directories((String) options.get("--dir"));
        Digester digester = digester(dtds, false, true, false);
        String config = (String) options.get("--config");
        if (log.isDebugEnabled()) {
            log.debug("Parsing configuration file '" + config + "'");
        }
        digester.push(new FacesConfigBean());
        fcb = parse(digester, config);
        if (log.isInfoEnabled()) {
            log.info("Generating HTML component classes");
        }

        // Generate concrete HTML component classes
        ComponentBean cbs[] = fcb.getComponents();
        for (i = 0; i < cbs.length; i++) {
            String componentClass = cbs[i].getComponentClass();
            if (componentClass.startsWith("javax.faces.component.html.")) {
                cb = cbs[i];
                generate();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);

}

From source file:gov.nih.nci.caintegrator.application.gpvisualizer.CaIntegratorRunVisualizer.java

/**
 * args[0] = visualizer task name args[1] = command line args[2] = debug
 * flag args[3] = OS required for running args[4] = CPU type required for
 * running args[5] = libdir on server for this task args[6] = CSV list of
 * downloadable files for inputs args[7] = CSV list of input parameter names
 * args[8] = CSV list of support file names args[9] = CSV list of support
 * file modification dates args[10] = server URL args[11] = LSID of task
 * args[12...n] = optional input parameter arguments
 *//*from   ww  w . ja v a  2  s.c  o  m*/
public static void main(String[] args) {
    String[] wellKnownNames = { RunVisualizerConstants.NAME, RunVisualizerConstants.COMMAND_LINE,
            RunVisualizerConstants.DEBUG, RunVisualizerConstants.OS, RunVisualizerConstants.CPU_TYPE,
            RunVisualizerConstants.LIBDIR, RunVisualizerConstants.DOWNLOAD_FILES, RunVisualizerConstants.LSID };
    int PARAM_NAMES = 7;
    int SUPPORT_FILE_NAMES = PARAM_NAMES + 1;
    int SUPPORT_FILE_DATES = SUPPORT_FILE_NAMES + 1;
    int SERVER = SUPPORT_FILE_DATES + 1;
    int LSID = SERVER + 1;
    int TASK_ARGS = LSID + 1;

    try {
        HashMap params = new HashMap();
        for (int i = 0; i < wellKnownNames.length; i++) {
            params.put(wellKnownNames[i], args[i]);
        }

        String name = (String) params.get(RunVisualizerConstants.NAME);
        StringTokenizer stParameterNames = new StringTokenizer(args[PARAM_NAMES], ", ");
        int argNum = TASK_ARGS;
        // when pulling parameters from the command line, don't assume that
        // all were provided.
        // some could be missing!
        while (stParameterNames.hasMoreTokens()) {
            String paramName = stParameterNames.nextToken();
            if (argNum < args.length) {
                String paramValue = args[argNum++];
                params.put(paramName, paramValue);
            } else {
                System.err.println("No value specified for " + paramName);
            }
        }
        URL source = new URL(args[SERVER]);

        StringTokenizer stFileNames = new StringTokenizer(args[SUPPORT_FILE_NAMES], ",");
        StringTokenizer stFileDates = new StringTokenizer(args[SUPPORT_FILE_DATES], ",");
        String[] supportFileNames = new String[stFileNames.countTokens()];
        long[] supportFileDates = new long[supportFileNames.length];
        String filename = null;
        String fileDate = null;
        int f = 0;
        while (stFileNames.hasMoreTokens()) {
            supportFileNames[f] = stFileNames.nextToken();
            if (stFileDates.hasMoreTokens()) {
                supportFileDates[f] = Long.parseLong(stFileDates.nextToken());
            } else {
                supportFileDates[f] = -1;
            }
            f++;
        }

        CaIntegratorRunVisualizer visualizer = new CaIntegratorRunVisualizer(params, supportFileNames,
                supportFileDates, new Applet());
        visualizer.run();
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

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

    try {//from  www. j  av a 2s. c  om

        // Perform setup operations
        if (log.isDebugEnabled()) {
            log.debug("Processing command line options");
        }
        Map options = options(args);
        String dtd = (String) options.get("--dtd");
        if (log.isDebugEnabled()) {
            log.debug("Configuring digester instance with public identifiers and DTD '" + dtd + "'");
        }
        StringTokenizer st = new StringTokenizer(dtd, "|");
        int arrayLen = st.countTokens();
        if (arrayLen == 0) {
            // PENDING I18n
            throw new Exception("No DTDs specified");
        }
        String[] dtds = new String[arrayLen];
        int i = 0;
        while (st.hasMoreTokens()) {
            dtds[i] = st.nextToken();
            i++;
        }
        directories((String) options.get("--dir"));
        Digester digester = digester(dtds, false, true, false);
        String config = (String) options.get("--config");
        if (log.isDebugEnabled()) {
            log.debug("Parsing configuration file '" + config + "'");
        }
        fcb = parse(digester, config);
        if (log.isInfoEnabled()) {
            log.info("Generating HTML component classes");
        }

        // Generate render-kit documentation
        // copy the static files to the output area
        copyResourceToFile("com/sun/faces/generate/facesdoc/index.html", new File(directory, "index.html"));
        copyResourceToFile("com/sun/faces/generate/facesdoc/stylesheet.css",
                new File(directory, "stylesheet.css"));

        generateAllRenderersFrame();
        generateRenderKitSummary();
        generateRenderersDocs();

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);

}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$
        System.out.println(// ww  w  . j av  a2s  .c  o  m
                "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$
        System.out.println(
                "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$
    } else {
        String url = args[1];
        String destdir = args[2];

        List parts = new ArrayList();
        int dir_from = 0;
        int dir_to = 0;
        int dir_fill = 0;
        int from = 0;
        int to = 0;
        int fill = 0;

        StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$
        boolean hasDir = (tk.countTokens() > 5);
        boolean inDir = hasDir;
        System.out.println("hasDir " + hasDir); //$NON-NLS-1$
        boolean inTag = false;
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken();
            if (token.equals("[")) //$NON-NLS-1$
            {
                inTag = true;
                continue;
            }
            if (token.equals("]")) //$NON-NLS-1$
            {
                inTag = false;
                if (inDir)
                    inDir = false;
                continue;
            }
            if (inTag) {
                int idx = token.indexOf('-');
                String s_from = token.substring(0, idx);
                int a_from = new Integer(s_from).intValue();
                int a_fill = s_from.length();
                int a_to = new Integer(token.substring(idx + 1)).intValue();
                if (inDir) {
                    dir_from = a_from;
                    dir_to = a_to;
                    dir_fill = a_fill;
                } else {
                    from = a_from;
                    to = a_to;
                    fill = a_fill;
                }
            } else {
                parts.add(token);
            }
        }

        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpGet main = new HttpGet(args[0]);
        HttpResponse res = client.execute(main);
        ;
        int main_rs = res.getStatusLine().getStatusCode();
        if (main_rs != 200) {
            System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$
            return;
        }

        for (int d = dir_from; d <= dir_to; d++) {
            String dir_number = "" + d; //$NON-NLS-1$
            if (dir_fill > 1) {
                dir_number = "000000" + d; //$NON-NLS-1$
                int dir_digits = (int) (Math.log(fill) / Math.log(10));
                System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$
                dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits),
                        dir_number.length());
            }
            for (int i = from; i <= to; i++) {
                try {
                    String number = "" + i; //$NON-NLS-1$
                    if (fill > 1) {
                        number = "000000" + i; //$NON-NLS-1$
                        int digits = (int) (Math.log(fill) / Math.log(10));
                        System.out.println("digits " + digits); //$NON-NLS-1$
                        number = number.substring(number.length() - (fill - digits), number.length());
                    }
                    int part = 0;
                    StringBuffer surl = new StringBuffer((String) parts.get(part++));
                    if (hasDir) {
                        surl.append(dir_number);
                        surl.append(parts.get(part++));
                    }
                    surl.append(number);
                    surl.append(parts.get(part++));
                    System.out.println("reading url " + surl); //$NON-NLS-1$

                    int indx = surl.toString().lastIndexOf('/');
                    StringBuffer sfile = new StringBuffer(destdir);
                    sfile.append("\\"); //$NON-NLS-1$
                    if (hasDir) {
                        sfile.append("dir_"); //$NON-NLS-1$
                        sfile.append(dir_number);
                        sfile.append("_"); //$NON-NLS-1$
                    }
                    sfile.append(surl.toString().substring(indx + 1));
                    File file = new File(sfile.toString());
                    if (file.exists()) {
                        file = new File("" + System.currentTimeMillis() + sfile.toString());
                    }
                    System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$

                    //                  URL iurl = createURLFromString(surl.toString());
                    HttpGet get = new HttpGet(surl.toString());

                    HttpResponse response = client.execute(get);
                    int result = response.getStatusLine().getStatusCode();
                    System.out.println("page http result " + result); //$NON-NLS-1$
                    if (result == 200) {
                        InputStream is = response.getEntity().getContent();
                        FileOutputStream fos = new FileOutputStream(file);
                        Utils.streamCopy(is, fos);
                        fos.close();
                    }
                } catch (Exception e) {
                    System.err.println(e);
                }
            }
        }
    }
}

From source file:com.sun.faces.generate.HtmlTaglibGenerator.java

/**
 * Main routine.//from  w  ww  . j  a v  a2  s  . c  o m
 */
public static void main(String args[]) throws Exception {

    try {
        // Perform setup operations
        if (log.isDebugEnabled()) {
            log.debug("Processing command line options");
        }
        Map options = options(args);
        String dtd = (String) options.get("--dtd");
        if (log.isDebugEnabled()) {
            log.debug("Configuring digester instance with public identifiers and DTD '" + dtd + "'");
        }
        StringTokenizer st = new StringTokenizer(dtd, "|");
        int arrayLen = st.countTokens();
        if (arrayLen == 0) {
            // PENDING I18n
            throw new Exception("No DTDs specified");
        }
        String[] dtds = new String[arrayLen];
        int i = 0;
        while (st.hasMoreTokens()) {
            dtds[i] = st.nextToken();
            i++;
        }
        copyright((String) options.get("--copyright"));
        directories((String) options.get("--tlddir"), false);
        Digester digester = digester(dtds, false, true, false);
        String config = (String) options.get("--config");
        loadOptionalTags((String) options.get("--tagdef"));
        if (log.isDebugEnabled()) {
            log.debug("Parsing configuration file '" + config + "'");
        }
        digester.push(new FacesConfigBean());
        fcb = parse(digester, config);
        if (log.isInfoEnabled()) {
            log.info("Generating Tag Library Descriptor file");
        }

        // Generate TLD File
        generateTld();

        // Generate Tag Handler Classes
        directories((String) options.get("--dir"), true);
        generateTagClasses();

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:com.moviejukebox.MovieJukebox.java

public static void main(String[] args) throws Throwable {
    JukeboxStatistics.setTimeStart(System.currentTimeMillis());

    // Create the log file name here, so we can change it later (because it's locked
    System.setProperty("file.name", LOG_FILENAME);
    PropertyConfigurator.configure("properties/log4j.properties");

    LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion());
    LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length()));
    LOG.info("https://github.com/YAMJ/yamj-v2");
    LOG.info("Copyright (c) 2004-2016 YAMJ Members");
    LOG.info("");
    LOG.info("This software is licensed under the GNU General Public License v3+");
    LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License");
    LOG.info("");
    LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : "");
    LOG.info("  Commit Date: {}", GIT.getCommitTime());
    LOG.info("   Build Date: {}", GIT.getBuildTime());
    LOG.info("");
    LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion());
    LOG.info("");

    if (!SystemTools.validateInstallation()) {
        LOG.info("ABORTING.");
        return;//from  w w  w .  j a va2s . c  o  m
    }

    String movieLibraryRoot = null;
    String jukeboxRoot = null;
    Map<String, String> cmdLineProps = new LinkedHashMap<>();

    try {
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if ("-v".equalsIgnoreCase(arg)) {
                // We've printed the version, so quit now
                return;
            } else if ("-t".equalsIgnoreCase(arg)) {
                String pin = args[++i];

                // load the apikeys.properties file
                if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
                    return;
                }

                // authorize to Trakt.TV
                TraktTV.getInstance().initialize().authorizeWithPin(pin);

                // We've authorized access to Trakt.TV, so quit now
                return;
            } else if ("-o".equalsIgnoreCase(arg)) {
                jukeboxRoot = args[++i];
                PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot);
            } else if ("-c".equalsIgnoreCase(arg)) {
                jukeboxClean = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE);
            } else if ("-k".equalsIgnoreCase(arg)) {
                setJukeboxPreserve(Boolean.TRUE);
            } else if ("-p".equalsIgnoreCase(arg)) {
                userPropertiesName = args[++i];
            } else if ("-i".equalsIgnoreCase(arg)) {
                skipIndexGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE);
            } else if ("-h".equalsIgnoreCase(arg)) {
                skipHtmlGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE);
            } else if ("-dump".equalsIgnoreCase(arg)) {
                dumpLibraryStructure = Boolean.TRUE;
            } else if ("-memory".equalsIgnoreCase(arg)) {
                showMemory = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE);
            } else if (arg.startsWith("-D")) {
                String propLine = arg.length() > 2 ? arg.substring(2) : args[++i];
                int propDiv = propLine.indexOf('=');
                if (-1 != propDiv) {
                    cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1));
                }
            } else if (arg.startsWith("-")) {
                help();
                return;
            } else {
                movieLibraryRoot = args[i];
            }
        }
    } catch (Exception error) {
        LOG.error("Wrong arguments specified");
        help();
        return;
    }

    // Save the name of the properties file for use later
    setProperty("userPropertiesName", userPropertiesName);

    LOG.info("Processing started at {}", new Date());
    LOG.info("");

    // Load the moviejukebox-default.properties file
    if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) {
        return;
    }

    // Load the user properties file "moviejukebox.properties"
    // No need to abort if we don't find this file
    // Must be read before the skin, because this may contain an override skin
    setPropertiesStreamName(userPropertiesName, Boolean.FALSE);

    // Grab the skin from the command-line properties
    if (cmdLineProps.containsKey(SKIN_DIR)) {
        setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR));
    }

    // Load the skin.properties file
    if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) {
        return;
    }

    // Load the skin-user.properties file (ignore the error)
    setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE);

    // Load the overlay.properties file (ignore the error)
    String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN);
    overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE)
            ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator)
            : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : "");
    setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE);

    // Load the apikeys.properties file
    if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
        return;
    }

    // This is needed to update the static reference for the API Keys in the pattern formatter
    // because the formatter is initialised before the properties files are read
    FilteringLayout.addApiKeys();

    // Load the rest of the command-line properties
    for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) {
        setProperty(propEntry.getKey(), propEntry.getValue());
    }

    // Read the information about the skin
    SkinProperties.readSkinVersion();
    // Display the information about the skin
    SkinProperties.printSkinVersion();

    StringBuilder properties = new StringBuilder("{");
    for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) {
        properties.append(propEntry.getKey());
        properties.append("=");
        properties.append(propEntry.getValue());
        properties.append(",");
    }
    properties.replace(properties.length() - 1, properties.length(), "}");

    // Print out the properties to the log file.
    LOG.debug("Properties: {}", properties.toString());

    // Check for mjb.skipIndexGeneration and set as necessary
    // This duplicates the "-i" functionality, but allows you to have it in the property file
    skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE);

    if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) {
        peopleScan = Boolean.TRUE;
        peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE);
        peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10);
        popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5);

        // Issue 1947: Cast enhancement - option to save all related files to a specific folder
        peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", "");
        if (isNotValidString(peopleFolder)) {
            peopleFolder = "";
        } else if (!peopleFolder.endsWith(File.separator)) {
            peopleFolder += File.separator;
        }
        StringTokenizer st = new StringTokenizer(
                PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| ");
        while (st.hasMoreTokens()) {
            PHOTO_EXTENSIONS.add(st.nextToken());
        }
    }

    // Check for mjb.skipHtmlGeneration and set as necessary
    // This duplicates the "-h" functionality, but allows you to have it in the property file
    skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE);

    // Look for the parameter in the properties file if it's not been set on the command line
    // This way we don't overwrite the setting if it's not found and defaults to FALSE
    showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE);

    // This duplicates the "-c" functionality, but allows you to have it in the property file
    jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE);

    MovieFilenameScanner.setSkipKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE));
    MovieFilenameScanner.setSkipRegexKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE));
    MovieFilenameScanner.setExtrasKeywords(
            tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| "));
    MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray(
            getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"),
            ",;|"));
    MovieFilenameScanner.setLanguageDetection(
            PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE));
    final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null);
    if (!languages.isEmpty()) {
        MovieFilenameScanner.clearLanguages();
        for (String lang : languages.getKeywords()) {
            String values = languages.get(lang);
            if (values != null) {
                MovieFilenameScanner.addLanguage(lang, values, values);
            } else {
                LOG.info("No values found for language code '{}'", lang);
            }
        }
    }
    final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords",
            "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV");
    MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords);

    String temp = getProperty("sorting.strip.prefixes");
    if (temp != null) {
        StringTokenizer st = new StringTokenizer(temp, ",");
        while (st.hasMoreTokens()) {
            String token = st.nextToken().trim();
            if (token.startsWith("\"") && token.endsWith("\"")) {
                token = token.substring(1, token.length() - 1);
            }
            Movie.addSortIgnorePrefixes(token.toLowerCase());
        }
    }

    enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE);
    enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE);
    enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE);

    // Check to see if don't have a root, check the property file
    if (StringTools.isNotValidString(movieLibraryRoot)) {
        movieLibraryRoot = getProperty("mjb.libraryRoot");
        if (StringTools.isValidString(movieLibraryRoot)) {
            LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot);
        } else {
            LOG.error("No library root found!");
            help();
            return;
        }
    }

    if (jukeboxRoot == null) {
        jukeboxRoot = getProperty("mjb.jukeboxRoot");
        if (jukeboxRoot == null) {
            LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors.");
        } else {
            LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot);
        }
    }

    File f = new File(movieLibraryRoot);
    if (f.exists() && f.isDirectory() && jukeboxRoot == null) {
        jukeboxRoot = movieLibraryRoot;
    }

    if (movieLibraryRoot == null) {
        help();
        return;
    }

    if (jukeboxRoot == null) {
        LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !");
        help();
        return;
    }

    if (!f.exists()) {
        LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot);
        return;
    }

    FileTools.initUnsafeChars();
    FileTools.initSubtitleExtensions();

    // make canonical names
    jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot);
    movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot);
    MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot);
    if (dumpLibraryStructure) {
        LOG.warn(
                "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated");
        ml.makeDumpStructure();
    } else {
        ml.generateLibrary();
    }

    // Now rename the log files
    renameLogFile();

    if (ScanningLimit.isLimitReached()) {
        LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.",
                ScanningLimit.getLimit());
        System.exit(EXIT_SCAN_LIMIT);
    } else {
        System.exit(EXIT_NORMAL);
    }
}