Example usage for java.util StringTokenizer StringTokenizer

List of usage examples for java.util StringTokenizer StringTokenizer

Introduction

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

Prototype

public StringTokenizer(String str) 

Source Link

Document

Constructs a string tokenizer for the specified string.

Usage

From source file:com.hzih.sslvpn.servlet.TelnetClientExample.java

/**
 * Main for the TelnetClientExample.// ww w .j a v  a2s  .c  o m
 * *
 */
public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        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 TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            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");

            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) {
                        if ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } 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.groupC1.control.network.TelnetClientExample.java

/***
 * Main for the TelnetClient./*from www . j a va 2  s.  c o m*/
 ***/
public static void main(String[] args) throws Exception {
    args = new String[] { "169.254.0.10", "10001" };
    FileOutputStream fout = null;
    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }
    String remoteip = args[0];
    int remoteport;
    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }
    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }
    tc = new org.apache.commons.net.telnet.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 TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClient");
            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");

            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) {
                        if ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).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 ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } 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:PopClean.java

public static void main(String args[]) {
    try {/*from  www . ja va 2s.  c  om*/
        String hostname = null, username = null, password = null;
        int port = 110;
        int sizelimit = -1;
        String subjectPattern = null;
        Pattern pattern = null;
        Matcher matcher = null;
        boolean delete = false;
        boolean confirm = true;

        // Handle command-line arguments
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-user"))
                username = args[++i];
            else if (args[i].equals("-pass"))
                password = args[++i];
            else if (args[i].equals("-host"))
                hostname = args[++i];
            else if (args[i].equals("-port"))
                port = Integer.parseInt(args[++i]);
            else if (args[i].equals("-size"))
                sizelimit = Integer.parseInt(args[++i]);
            else if (args[i].equals("-subject"))
                subjectPattern = args[++i];
            else if (args[i].equals("-debug"))
                debug = true;
            else if (args[i].equals("-delete"))
                delete = true;
            else if (args[i].equals("-force")) // don't confirm
                confirm = false;
        }

        // Verify them
        if (hostname == null || username == null || password == null || sizelimit == -1)
            usage();

        // Make sure the pattern is a valid regexp
        if (subjectPattern != null) {
            pattern = Pattern.compile(subjectPattern);
            matcher = pattern.matcher("");
        }

        // Say what we are going to do
        System.out
                .println("Connecting to " + hostname + " on port " + port + " with username " + username + ".");
        if (delete) {
            System.out.println("Will delete all messages longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        } else {
            System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        }

        // If asked to delete, ask for confirmation unless -force is given
        if (delete && confirm) {
            System.out.println();
            System.out.print("Do you want to proceed (y/n) [n]: ");
            System.out.flush();
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            String response = console.readLine();
            if (!response.equals("y")) {
                System.out.println("No messages deleted.");
                System.exit(0);
            }
        }

        // Connect to the server, and set up streams
        s = new Socket(hostname, port);
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

        // Read the welcome message from the server, confirming it is OK.
        System.out.println("Connected: " + checkResponse());

        // Now log in
        send("USER " + username); // Send username, wait for response
        send("PASS " + password); // Send password, wait for response
        System.out.println("Logged in");

        // Check how many messages are waiting, and report it
        String stat = send("STAT");
        StringTokenizer t = new StringTokenizer(stat);
        System.out.println(t.nextToken() + " messages in mailbox.");
        System.out.println("Total size: " + t.nextToken());

        // Get a list of message numbers and sizes
        send("LIST"); // Send LIST command, wait for OK response.
        // Now read lines from the server until we get . by itself
        List msgs = new ArrayList();
        String line;
        for (;;) {
            line = in.readLine();
            if (line == null)
                throw new IOException("Unexpected EOF");
            if (line.equals("."))
                break;
            msgs.add(line);
        }

        // Now loop through the lines we read one at a time.
        // Each line should specify the message number and its size.
        int nummsgs = msgs.size();
        for (int i = 0; i < nummsgs; i++) {
            String m = (String) msgs.get(i);
            StringTokenizer st = new StringTokenizer(m);
            int msgnum = Integer.parseInt(st.nextToken());
            int msgsize = Integer.parseInt(st.nextToken());

            // If the message is too small, ignore it.
            if (msgsize <= sizelimit)
                continue;

            // If we're listing messages, or matching subject lines
            // find the subject line for this message
            String subject = null;
            if (!delete || pattern != null) {
                subject = getSubject(msgnum); // get the subject line

                // If we couldn't find a subject, skip the message
                if (subject == null)
                    continue;

                // If this subject does not match the pattern, then
                // skip the message
                if (pattern != null) {
                    matcher.reset(subject);
                    if (!matcher.matches())
                        continue;
                }

                // If we are listing, list this message
                if (!delete) {
                    System.out.println("Subject " + msgnum + ": " + subject);
                    continue; // so we never delete it
                }
            }

            // If we were asked to delete, then delete the message
            if (delete) {
                send("DELE " + msgnum);
                if (pattern == null)
                    System.out.println("Deleted message " + msgnum);
                else
                    System.out.println("Deleted message " + msgnum + ": " + subject);
            }
        }

        // When we're done, log out and shutdown the connection
        shutdown();
    } catch (Exception e) {
        // If anything goes wrong print exception and show usage
        System.err.println(e);
        usage();
        // Always try to shutdown nicely so the server doesn't hang on us
        shutdown();
    }
}

From source file:edu.asu.bscs.csiebler.calculatorrpc.CalcJavaClient.java

public static void main(String args[]) {
    try {//from w  w w  .j a  v a2 s . c  o  m
        String url = "http://127.0.0.1:8080/";
        if (args.length > 0) {
            url = args[0];
        }
        CalcJavaClient cjc = new CalcJavaClient(url);
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >");
        String inStr = stdin.readLine();
        StringTokenizer st = new StringTokenizer(inStr);
        String opn = st.nextToken();
        while (!opn.equalsIgnoreCase("end")) {
            if (opn.equalsIgnoreCase("+")) {
                double result = cjc.add(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("-")) {
                double result = cjc.subtract(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("*")) {
                double result = cjc.multiply(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("/")) {
                double result = cjc.divide(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            }
            System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >");
            inStr = stdin.readLine();
            st = new StringTokenizer(inStr);
            opn = st.nextToken();
        }
    } catch (Exception e) {
        System.out.println("Oops, you didn't enter the right stuff");
    }
}

From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java

/**
 *
 * @param args//from   ww  w .  jav a2 s .com
 */
public static void main(String args[]) {
    try {
        String url = "http://127.0.0.1:8080/";

        if (args.length > 0) {
            url = args[0];
        }

        WaypointServerStub cjc = new WaypointServerStub(url);
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print(
                "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg  remove Toreros >");
        String inStr = stdin.readLine();
        StringTokenizer st = new StringTokenizer(inStr);
        String opn = st.nextToken();

        while (!opn.equalsIgnoreCase("end")) {
            switch (opn) {
            case "remove": {
                boolean result = cjc.remove(st.nextToken());
                System.out.println("response: " + result);
                break;
            }
            case "get": {
                Waypoint result = cjc.get(st.nextToken());
                System.out.println("response: " + result.toJsonString());
                break;
            }
            case "getNames": {
                String[] result = cjc.getNames();
                for (int i = 0; i < result.length; i++) {
                    System.out.println("response[" + i + "] is " + result[i]);
                }
                break;
            }
            case "getCategoryNames": {
                String[] result = cjc.getCategoryNames();
                for (int i = 0; i < result.length; i++) {
                    System.out.println("response[" + i + "] is " + result[i]);
                }
                break;
            }
            case "getNamesInCategory": {
                String[] result = cjc.getNamesInCategory(st.nextToken());
                for (int i = 0; i < result.length; i++) {
                    System.out.println("response[" + i + "] is " + result[i]);
                }
                break;
            }
            case "dist": {
                double result = cjc.distanceGCTo(st.nextToken(), st.nextToken());
                System.out.println("response: " + result);
                break;
            }
            case "bear": {
                double result = cjc.bearingGCInitTo(st.nextToken(), st.nextToken());
                System.out.println("response: " + result);
                break;
            }
            default: {
                break;
            }
            }

            System.out.print(
                    "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg  remove Toreros >");
            inStr = stdin.readLine();
            st = new StringTokenizer(inStr);
            opn = st.nextToken();
        }
    } catch (Exception e) {
        System.out.println("Oops, you didn't enter the right stuff");
    }
}

From source file:Main.java

private static String[] tokenize(String str) {
    StringTokenizer tokenizer = new StringTokenizer(str);
    String[] arr = new String[tokenizer.countTokens()];
    int i = 0;//from w ww  .j  ava  2  s . c o m
    while (tokenizer.hasMoreTokens()) {
        arr[i++] = tokenizer.nextToken();
    }
    return arr;
}

From source file:Main.java

public static String titleCase(String s) {
    StringBuilder rv = new StringBuilder(s.length());
    StringTokenizer strtok = new StringTokenizer(s);

    while (strtok.hasMoreTokens()) {
        String word = strtok.nextToken();
        String firstLetter = word.substring(0, 1);
        String restOfWord = word.substring(1);

        if (rv.length() > 0)
            rv.append(" ");
        rv.append(firstLetter.toUpperCase());
        rv.append(restOfWord.toLowerCase());
    }//  w w w.ja  va 2  s .  co  m

    return rv.toString();
}

From source file:Main.java

public static ArrayList<String> getInput() {
    ArrayList<String> result = new ArrayList<String>(10);
    String line;/*from   w  w  w . j av a  2 s  .  c o  m*/
    try {
        line = new BufferedReader(new InputStreamReader(System.in)).readLine();
        if (line != null) {
            StringTokenizer st = new StringTokenizer(line);
            while (st.hasMoreTokens())
                result.add(st.nextToken());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:Main.java

public static String getThreadName(Thread thr) {
    if (thr == null)
        return "null";

    // This depends on the formatting in SelectReaderThread and CorbaConnectionImpl.
    // Pattern for SelectReaderThreads:
    // SelectReaderThread CorbaConnectionImpl[ <host> <post> <state>]
    // Any other pattern in the Thread's name is just returned.
    String name = thr.getName();/*  w w  w .ja v a2  s  . com*/
    StringTokenizer st = new StringTokenizer(name);
    int numTokens = st.countTokens();
    if (numTokens != 5)
        return name;

    String[] tokens = new String[numTokens];
    for (int ctr = 0; ctr < numTokens; ctr++)
        tokens[ctr] = st.nextToken();

    if (!tokens[0].equals("SelectReaderThread"))
        return name;

    return "SelectReaderThread[" + tokens[2] + ":" + tokens[3] + "]";
}

From source file:Main.java

public static String normalizeSpace(String str) {
    if (!isNullOrEmpty(str)) {
        StringTokenizer st = new StringTokenizer(str);
        if (st.hasMoreTokens()) {

            StringBuffer sb = new StringBuffer(str.length());
            while (true) {
                sb.append(st.nextToken());
                if (st.hasMoreTokens()) {
                    sb.append(' ');
                } else {
                    break;
                }/*from  ww w  . j  ava2s. c om*/
            }
            return sb.toString();
        } else {
            return "";
        }
    } else {
        return str;
    }
}