Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

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

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:ReplacingStringTokenizer.java

public static void main(String[] args) {
    String input = "But I'm not dead yet! I feel happy!";
    StringTokenizer stoke = new StringTokenizer(input);
    while (stoke.hasMoreElements())
        System.out.println(stoke.nextToken());
    System.out.println(Arrays.asList(input.split(" ")));
}

From source file:searchengine.SearchEngine.java

/**
 * @param args the command line arguments
 *//*from  ww w.j av a  2s  .co m*/
public static void main(String[] args) {
    ArrayList<String> library = new ArrayList<String>();
    ArrayList<String> tokenList = new ArrayList<String>();
    library.add("The red car is faster than the blue car");
    library.add("The blue car is slower than the green car");
    library.add("The green car is slower than the purple truck");
    library.add("The purple truck is faster than the red car");

    System.out.println("Compiling");
    int excerptID = 1;
    int tokenID = 1;
    for (String s : library) {
        System.out.println("INSERT INTO `excerpt`(`id`,`text`)VALUES(" + excerptID++ + ",'" + s + "'); ");
        StringTokenizer st = new StringTokenizer(s, " ");
        while (st.hasMoreElements()) {
            String token = st.nextToken().toLowerCase();
            System.out.println("INSERT IGNORE INTO `token`(`id`,`text`)VALUES(" + tokenID++ + ",'" + s + "');");
            System.out.println("INSERT IGNORE INTO `excerpt_token`(`excerpt_id`,`token_id`)VALUES(" + x++ + ",'"
                    + s + "');");
        }
    }

    System.out.println("Printing");
    int x = 1;
    for (String s : library) {
        System.out.println("INSERT INTO `excerpt`(`id`,`text`)VALUES(" + x++ + ",'" + s + "'); ");
    }
    x = 1;
    for (String s : tokenList) {

    }
    x = 1;
}

From source file:MainClass.java

public static void main(String args[]) {
    // void copyToClipboard() {
    String toClipboard = "Hello from Java!";
    StringSelection ss = new StringSelection(toClipboard);
    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    clip.setContents(ss, ss);//w w w . j a  v a2s . c o m
    // Paste
    clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable contents = clip.getContents(new MainClass().getClass());
    if (contents == null)
        System.out.println("The clipboard is empty.");
    else {
        if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                String data = (String) contents.getTransferData(DataFlavor.stringFlavor);
                if (data == null)
                    System.out.println("null");
                else {
                    StringTokenizer st = new StringTokenizer(data, "\n");
                    while (st.hasMoreElements())
                        System.out.println(st.nextToken());
                }
            } catch (IOException ex) {
                System.out.println("IOException");
            } catch (UnsupportedFlavorException ex) {
                System.out.println("UnsupportedFlavorException");
            }
        } else
            System.out.println("Wrong flavor.");
    }

}

From source file:StringBufferCommaList.java

public static void main(String[] args) {
    StringTokenizer st = new StringTokenizer("Alpha Bravo Charlie");
    StringBuffer sb = new StringBuffer();
    while (st.hasMoreElements()) {
        sb.append(st.nextToken());/*from  w  ww .  j a  v a  2 s .c o m*/
        if (st.hasMoreElements()) {
            sb.append(", ");
        }
    }
    System.out.println(sb);
}

From source file:com.ibm.crail.storage.StorageServer.java

public static void main(String[] args) throws Exception {
    Logger LOG = CrailUtils.getLogger();
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);
    CrailConstants.printConf();//  ww  w.  j a  va  2 s .  c o  m
    CrailConstants.verify();

    int splitIndex = 0;
    for (String param : args) {
        if (param.equalsIgnoreCase("--")) {
            break;
        }
        splitIndex++;
    }

    //default values
    StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ",");
    if (!tokenizer.hasMoreTokens()) {
        throw new Exception("No storage types defined!");
    }
    String storageName = tokenizer.nextToken();
    int storageType = 0;
    HashMap<String, Integer> storageTypes = new HashMap<String, Integer>();
    storageTypes.put(storageName, storageType);
    for (int type = 1; tokenizer.hasMoreElements(); type++) {
        String name = tokenizer.nextToken();
        storageTypes.put(name, type);
    }
    int storageClass = -1;

    //custom values
    if (args != null) {
        Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build();
        Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg()
                .build();
        Options options = new Options();
        options.addOption(typeOption);
        options.addOption(classOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex));
            if (line.hasOption(typeOption.getOpt())) {
                storageName = line.getOptionValue(typeOption.getOpt());
                storageType = storageTypes.get(storageName).intValue();
            }
            if (line.hasOption(classOption.getOpt())) {
                storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Storage tier", options);
            System.exit(-1);
        }
    }
    if (storageClass < 0) {
        storageClass = storageType;
    }

    StorageTier storageTier = StorageTier.createInstance(storageName);
    if (storageTier == null) {
        throw new Exception("Cannot instantiate datanode of type " + storageName);
    }

    String extraParams[] = null;
    splitIndex++;
    if (args.length > splitIndex) {
        extraParams = new String[args.length - splitIndex];
        for (int i = splitIndex; i < args.length; i++) {
            extraParams[i - splitIndex] = args[i];
        }
    }
    storageTier.init(conf, extraParams);
    storageTier.printConf(LOG);

    RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcClient.init(conf, args);
    rpcClient.printConf(LOG);

    ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList();
    ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>();
    while (!namenodeList.isEmpty()) {
        InetSocketAddress address = namenodeList.poll();
        RpcConnection connection = rpcClient.connect(address);
        connectionList.add(connection);
    }
    RpcConnection rpcConnection = connectionList.peek();
    if (connectionList.size() > 1) {
        rpcConnection = new RpcDispatcher(connectionList);
    }
    LOG.info("connected to namenode(s) " + rpcConnection.toString());

    StorageServer server = storageTier.launchServer();
    StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass),
            server.getAddress(), rpcConnection);

    HashMap<Long, Long> blockCount = new HashMap<Long, Long>();
    long sumCount = 0;
    while (server.isAlive()) {
        StorageResource resource = server.allocateResource();
        if (resource == null) {
            break;
        } else {
            storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey());
            DataNodeStatistics stats = storageRpc.getDataNode();
            long newCount = stats.getFreeBlockCount();
            long serviceId = stats.getServiceId();

            long oldCount = 0;
            if (blockCount.containsKey(serviceId)) {
                oldCount = blockCount.get(serviceId);
            }
            long diffCount = newCount - oldCount;
            blockCount.put(serviceId, newCount);
            sumCount += diffCount;
            LOG.info("datanode statistics, freeBlocks " + sumCount);
        }
    }

    while (server.isAlive()) {
        DataNodeStatistics stats = storageRpc.getDataNode();
        long newCount = stats.getFreeBlockCount();
        long serviceId = stats.getServiceId();

        long oldCount = 0;
        if (blockCount.containsKey(serviceId)) {
            oldCount = blockCount.get(serviceId);
        }
        long diffCount = newCount - oldCount;
        blockCount.put(serviceId, newCount);
        sumCount += diffCount;

        LOG.info("datanode statistics, freeBlocks " + sumCount);
        Thread.sleep(2000);
    }
}

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   www. j a  v  a 2s . c  o m*/
    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:org.jabsorb.JSONRPCBridge.java

public static void main(String[] args) throws Exception {
    //String string="{\"id\":1,\"method\":\"test.echoList\",\"params\":[[1,2,3,4,5,6,7,8,9]]}";
    String string = "{\"id\":1,\"method\":\"test.echoList\",\"params\":[{\"a\":123,\"b\":456}]}";
    JSONObject jsonReq = new JSONObject(string);
    // #1: Parse the request
    final String encodedMethod;
    final Object requestId;
    final JSONArray arguments;
    final JSONArray fixups;

    encodedMethod = jsonReq.getString("method");
    arguments = jsonReq.getJSONArray("params");
    requestId = jsonReq.opt("id");
    fixups = jsonReq.optJSONArray("fixups");

    if (log.isDebugEnabled()) {
        if (fixups != null) {
            log.debug("call " + encodedMethod + "(" + arguments + ")" + ", requestId=" + requestId);
        } else {//from w  ww .j ava 2 s  .  com
            log.debug("call " + encodedMethod + "(" + arguments + ")" + ", fixups=" + fixups + ", requestId="
                    + requestId);
        }
    }

    // apply the fixups (if any) to the parameters. This will result
    // in a JSONArray that might have circular references-- so
    // the toString method (or anything that internally tries to traverse
    // the JSON (without being aware of this) should not be called after this
    // point

    if (fixups != null) {
        try {
            for (int i = 0; i < fixups.length(); i++) {
                JSONArray assignment = fixups.getJSONArray(i);
                JSONArray fixup = assignment.getJSONArray(0);
                JSONArray original = assignment.getJSONArray(1);
                //applyFixup(arguments, fixup, original);
            }
        } catch (JSONException e) {
            log.error("error applying fixups", e);
        }
    }

    // #2: Get the name of the class and method from the encodedMethod
    final String className;
    final String methodName;
    {
        StringTokenizer t = new StringTokenizer(encodedMethod, ".");
        if (t.hasMoreElements()) {
            className = t.nextToken();
        } else {
            className = null;
        }
        if (t.hasMoreElements()) {
            methodName = t.nextToken();
        } else {
            methodName = null;
        }
    }
    // #3: Get the id of the object (if it exists) from the className
    // (in the format: ".obj#<objectID>")
    final int objectID;
    {
        final int objectStartIndex = encodedMethod.indexOf('[');
        final int objectEndIndex = encodedMethod.indexOf(']');
        if (encodedMethod.startsWith(OBJECT_METHOD_PREFIX) && (objectStartIndex != -1) && (objectEndIndex != -1)
                && (objectStartIndex < objectEndIndex)) {
            objectID = Integer.parseInt(encodedMethod.substring(objectStartIndex + 1, objectEndIndex));
        } else {
            objectID = 0;
        }
    }
    JSONRPCBridge bridge = new JSONRPCBridge();
    bridge.registerObject("test", new Test());
    // #5: Get the object to act upon and the possible method that could be
    // called on it
    final Map methodMap;
    final Object javascriptObject;
    AccessibleObject accessibleObject = null;
    try {
        javascriptObject = bridge.getObjectContext(objectID, className);
        methodMap = bridge.getAccessibleObjectMap(objectID, className, methodName);
        // #6: Resolve the method
        accessibleObject = AccessibleObjectResolver.resolveMethod(methodMap, methodName, arguments, ser);
        if (accessibleObject == null) {
            throw new NoSuchMethodException(JSONRPCResult.MSG_ERR_NOMETHOD);
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    final Class[] parameterTypes;
    final boolean isConstructor = accessibleObject instanceof Constructor;
    if (isConstructor) {
        parameterTypes = ((Constructor) accessibleObject).getParameterTypes();
    } else {
        parameterTypes = ((Method) accessibleObject).getParameterTypes();
    }

    // Unmarshall arguments
    final Object javaArgs[] = unmarshallArgs(parameterTypes, arguments, ser);
}

From source file:Main.java

/**
 * This fucntion parse database id to retrieve UUID, Major and Minor
 * @param id//from   ww w. java2 s . c  om
 * @return
 */
public static List<String> parseId(String id) {
    List<String> list = new ArrayList<String>();
    StringTokenizer token = new StringTokenizer(id, ".");
    while (token.hasMoreElements()) {
        list.add((String) token.nextElement());
    }

    return list;
}

From source file:Main.java

protected static String[] split(final String str, final String delimiter) {
    if (str == null || str.trim().length() == 0) {
        return EMPTY_STRINGS;
    }/*from   ww  w  . j  a  v a 2 s .  c  o m*/
    final List<String> list = new ArrayList<String>();
    final StringTokenizer st = new StringTokenizer(str, delimiter);
    while (st.hasMoreElements()) {
        list.add(st.nextToken());
    }
    return (String[]) list.toArray(new String[list.size()]);
}

From source file:Main.java

public static ArrayList splitStringByCharC(String str, String c) {
    StringTokenizer en = new StringTokenizer(str, c);
    ArrayList vec = new ArrayList();
    while (en.hasMoreElements())
        vec.add(en.nextElement());/*w  ww  . j ava  2  s .c o  m*/
    return vec;
}