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:com.ok2c.lightmtp.examples.SendMailExample.java

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

    if (args.length < 3) {
        System.out.println("Usage: sender recipient1[;recipient2;recipient3;...] file");
        System.exit(0);//from www.  jav  a  2  s .co m
    }

    String sender = args[0];
    List<String> recipients = new ArrayList<String>();
    StringTokenizer tokenizer = new StringTokenizer(args[1], ";");
    while (tokenizer.hasMoreTokens()) {
        String s = tokenizer.nextToken();
        s = s.trim();
        if (s.length() > 0) {
            recipients.add(s);
        }
    }

    File src = new File(args[2]);
    if (!src.exists()) {
        System.out.println("File '" + src + "' does not exist");
        System.exit(0);
    }

    DeliveryRequest request = new BasicDeliveryRequest(sender, recipients, new FileSource(src));

    MailUserAgent mua = new DefaultMailUserAgent(TransportType.SMTP, IOReactorConfig.DEFAULT);
    mua.start();

    try {

        InetSocketAddress address = new InetSocketAddress("localhost", 2525);

        Future<DeliveryResult> future = mua.deliver(new SessionEndpoint(address), 0, request, null);

        DeliveryResult result = future.get();
        System.out.println("Delivery result: " + result);

    } finally {
        mua.shutdown();
    }
}

From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java

public static void main(String[] args) {
    try {/*  ww  w .  j  av a 2 s . c om*/
        BasicConfigurator.configure();
        //loadProperties();

        if (args.length < 2) {
            System.out.println("Usage: BuildTestbed <testbedID> <inputfile>");
            System.exit(0);
        }

        int testbedID = Integer.parseInt(args[0]);
        String filename = args[1];
        Connection conn = null;
        Statement statement = null;
        MoteSqlAdapter adapter = new MoteSqlAdapter();
        Map<Integer, Mote> motes = adapter.readMotes();

        log.info(motes);

        String connStr = System.getProperty("nestbed.options.databaseConnectionString");
        log.info("connStr: " + connStr);

        conn = DriverManager.getConnection(connStr);
        statement = conn.createStatement();

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));

        String line;
        while ((line = in.readLine()) != null) {
            StringTokenizer tokenizer = new StringTokenizer(line);
            int address = Integer.parseInt(tokenizer.nextToken());
            String serial = tokenizer.nextToken();
            int xLoc = Integer.parseInt(tokenizer.nextToken());
            int yLoc = Integer.parseInt(tokenizer.nextToken());

            log.info("Input Mote:\n" + "-----------\n" + "address:  " + address + "\n" + "serial:   " + serial
                    + "\n" + "xLoc:     " + xLoc + "\n" + "yLoc:     " + yLoc);

            for (Mote i : motes.values()) {
                if (i.getMoteSerialID().equals(serial)) {
                    String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress,"
                            + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", "
                            + address + ", " + xLoc + ", " + yLoc + ")";
                    log.info(query);
                    statement.executeUpdate(query);
                }
            }
        }
        conn.commit();
    } catch (Exception ex) {
        log.error("Exception in main", ex);
    }
}

From source file:Main.java

public static void main(String[] args) {

    StringTokenizer st = new StringTokenizer("tutorial from java2s.com");

    // counting tokens
    System.out.println("Total tokens : " + st.countTokens());

    // checking tokens
    while (st.hasMoreTokens()) {
        System.out.println("Next token : " + st.nextToken());
    }//w  w  w. jav a2s .  co m
}

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

public static void main(String args[]) {
    try {/*from  w  ww  .ja  va  2 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:info.bitoo.utils.BiToorrentRemaker.java

public static void main(String[] args) throws IOException, TOTorrentException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from   w  ww.j  a v  a2 s.  com
    try {
        cmd = parser.parse(createCommandLineOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }

    StringTokenizer stLocations = new StringTokenizer(cmd.getOptionValue("l"), "|");
    List locations = new ArrayList(stLocations.countTokens());

    while (stLocations.hasMoreTokens()) {
        URL locationURL = new URL((String) stLocations.nextToken());
        locations.add(locationURL.toString());
    }

    String torrentFileName = cmd.getOptionValue("t");

    File torrentFile = new File(torrentFileName);

    TOTorrentDeserialiseImpl torrent = new TOTorrentDeserialiseImpl(torrentFile);

    torrent.setAdditionalListProperty("alternative locations", locations);

    torrent.serialiseToBEncodedFile(torrentFile);

}

From source file:edu.gslis.ts.RunQuery.java

public static void main(String[] args) {
    try {//from w w w. ja  v a 2 s.c o  m
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String inputPath = cmd.getOptionValue("input");
        String eventsPath = cmd.getOptionValue("events");
        String stopPath = cmd.getOptionValue("stop");
        int queryId = Integer.valueOf(cmd.getOptionValue("query"));

        List<String> ids = FileUtils.readLines(new File(inputPath + File.separator + "ids.txt"));

        Stopper stopper = new Stopper(stopPath);
        Map<Integer, FeatureVector> queries = readEvents(eventsPath, stopper);

        FeatureVector query = queries.get(queryId);

        Pairtree ptree = new Pairtree();
        Bag<String> words = new HashBag<String>();

        for (String streamId : ids) {

            String ppath = ptree.mapToPPath(streamId.replace("-", ""));

            String inpath = inputPath + File.separator + ppath + File.separator + streamId + ".xz";
            //                System.out.println(inpath);
            File infile = new File(inpath);
            InputStream in = new XZInputStream(new FileInputStream(infile));

            TTransport inTransport = new TIOStreamTransport(new BufferedInputStream(in));
            TBinaryProtocol inProtocol = new TBinaryProtocol(inTransport);
            inTransport.open();
            final StreamItem item = new StreamItem();

            while (true) {
                try {
                    item.read(inProtocol);
                    //                        System.out.println("Read " + item.stream_id);

                } catch (TTransportException tte) {
                    // END_OF_FILE is used to indicate EOF and is not an exception.
                    if (tte.getType() != TTransportException.END_OF_FILE)
                        tte.printStackTrace();
                    break;
                }
            }

            // Do something with this document...
            String docText = item.getBody().getClean_visible();

            StringTokenizer itr = new StringTokenizer(docText);
            while (itr.hasMoreTokens()) {
                words.add(itr.nextToken());
            }

            inTransport.close();

        }

        for (String term : words.uniqueSet()) {
            System.out.println(term + ":" + words.getCount(term));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.petendi.ethereum.secure.proxy.Application.java

public static void main(String[] args) {

    try {/*from   w w  w  . ja v  a2s .  c  om*/
        cmdLineResult = new CmdLineResult();
        cmdLineResult.parseArguments(args);
    } catch (CmdLineException e) {
        System.out.println(e.getMessage());
        System.out.println("Usage:");
        cmdLineResult.printExample();
        System.exit(-1);
        return;
    }

    File workingDirectory = new File(System.getProperty("user.home"));
    if (cmdLineResult.getWorkingDirectory().length() > 0) {
        workingDirectory = new File(cmdLineResult.getWorkingDirectory()).getAbsoluteFile();
    }

    ArgumentList argumentList = new ArgumentList();
    argumentList.setWorkingDirectory(workingDirectory);
    File certificate = new File(workingDirectory, "seccoco-secured/cert.p12");
    if (certificate.exists()) {
        char[] passwd = null;
        if (cmdLineResult.getPassword() != null) {
            System.out.println("Using password from commandline argument - DON'T DO THIS IN PRODUCTION !!");
            passwd = cmdLineResult.getPassword().toCharArray();
        } else {
            Console console = System.console();
            if (console != null) {
                passwd = console.readPassword("[%s]", "Enter application password:");
            } else {
                System.out.print("No suitable console found for entering password");
                System.exit(-1);
            }
        }
        argumentList.setTokenPassword(passwd);
    }
    try {
        SeccocoFactory seccocoFactory = new SeccocoFactory("seccoco-secured", argumentList);
        seccoco = seccocoFactory.create();
    } catch (InitializationException e) {
        System.out.println(e.getMessage());
        System.exit(-1);
    }
    try {
        System.out.println("Connecting to Ethereum RPC at " + cmdLineResult.getUrl());
        URL url = new URL(cmdLineResult.getUrl());
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        String additionalHeaders = cmdLineResult.getAdditionalHeaders();
        if (additionalHeaders != null) {
            StringTokenizer tokenizer = new StringTokenizer(additionalHeaders, ",");
            while (tokenizer.hasMoreTokens()) {
                String keyValue = tokenizer.nextToken();
                StringTokenizer innerTokenizer = new StringTokenizer(keyValue, ":");
                headers.put(innerTokenizer.nextToken(), innerTokenizer.nextToken());
            }
        }
        settings = new Settings(cmdLineResult.isExposeWhisper(), headers);
        jsonRpcHttpClient = new JsonRpcHttpClient(url);
        jsonRpcHttpClient.setRequestListener(new JsonRpcRequestListener());

        jsonRpcHttpClient.invoke("eth_protocolVersion", null, Object.class, headers);
        if (cmdLineResult.isExposeWhisper()) {
            jsonRpcHttpClient.invoke("shh_version", null, Object.class, headers);
        }
        System.out.println("Connection succeeded");
    } catch (Throwable e) {
        System.out.println("Connection failed: " + e.getMessage());
        System.exit(-1);
    }
    SpringApplication app = new SpringApplication(Application.class);
    app.setBanner(new Banner() {
        @Override
        public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
            //send the Spring Boot banner to /dev/null
        }
    });
    app.run(new String[] {});
}

From source file:com.glaf.jbpm.action.MultiPooledTaskInstanceAction.java

public static void main(String[] args) throws Exception {
    String actorIdxy = "{joy,sam},{pp,qq},{kit,cora},{eyb2000,huangcw}";
    StringTokenizer st2 = new StringTokenizer(actorIdxy, ";");
    while (st2.hasMoreTokens()) {
        String elem2 = st2.nextToken();
        if (StringUtils.isNotEmpty(elem2)) {
            elem2 = elem2.trim();/*  w  ww . java2 s .  c om*/
            if ((elem2.length() > 0 && elem2.charAt(0) == '{') && elem2.endsWith("}")) {
                elem2 = elem2.substring(elem2.indexOf("{") + 1, elem2.indexOf("}"));
                Set<String> actorIds = new HashSet<String>();
                StringTokenizer st4 = new StringTokenizer(elem2, ",");
                while (st4.hasMoreTokens()) {
                    String elem4 = st4.nextToken();
                    elem4 = elem4.trim();
                    if (elem4.length() > 0) {
                        actorIds.add(elem4);
                    }
                }
                System.out.println(actorIds);
            }
        }
    }
}

From source file:ISMAGS.CommandLineInterface.java

public static void main(String[] args) throws IOException {
    String folder = null, files = null, motifspec = null, output = null;

    Options opts = new Options();
    opts.addOption("folder", true, "Folder name");
    opts.addOption("linkfiles", true,
            "Link files seperated by spaces (format: linktype[char] directed[d/u] filename)");
    opts.addOption("motif", true, "Motif description by two strings (format: linktypes)");
    opts.addOption("output", true, "Output file name");

    CommandLineParser parser = new PosixParser();
    try {// w  w w .ja va  2  s  . com
        CommandLine cmd = parser.parse(opts, args);
        if (cmd.hasOption("folder")) {
            folder = cmd.getOptionValue("folder");
        }
        if (cmd.hasOption("linkfiles")) {
            files = cmd.getOptionValue("linkfiles");
        }
        if (cmd.hasOption("motif")) {
            motifspec = cmd.getOptionValue("motif");
        }
        if (cmd.hasOption("output")) {
            output = cmd.getOptionValue("output");
        }
    } catch (ParseException e) {
        Die("Error: Parsing error");
    }

    if (print) {
        printBanner(folder, files, motifspec, output);
    }

    if (folder == null || files == null || motifspec == null || output == null) {
        Die("Error: not all options are provided");
    } else {
        ArrayList<String> linkfiles = new ArrayList<String>();
        ArrayList<String> linkTypes = new ArrayList<String>();
        ArrayList<String> sourcenetworks = new ArrayList<String>();
        ArrayList<String> destinationnetworks = new ArrayList<String>();
        ArrayList<Boolean> directed = new ArrayList<Boolean>();
        StringTokenizer st = new StringTokenizer(files, " ");
        while (st.hasMoreTokens()) {
            linkTypes.add(st.nextToken());
            directed.add(st.nextToken().equals("d"));
            sourcenetworks.add(st.nextToken());
            destinationnetworks.add(st.nextToken());
            linkfiles.add(folder + st.nextToken());
        }
        ArrayList<LinkType> allLinkTypes = new ArrayList<LinkType>();
        HashMap<Character, LinkType> typeTranslation = new HashMap<Character, LinkType>();
        for (int i = 0; i < linkTypes.size(); i++) {
            String n = linkTypes.get(i);
            char nn = n.charAt(0);
            LinkType t = typeTranslation.get(nn);
            if (t == null) {
                t = new LinkType(directed.get(i), n, i, nn, sourcenetworks.get(i), destinationnetworks.get(i));
            }
            allLinkTypes.add(t);
            typeTranslation.put(nn, t);
        }
        if (print) {
            System.out.println("Reading network..");
        }
        Network network = Network.readNetworkFromFiles(linkfiles, allLinkTypes);

        Motif motif = getMotif(motifspec, typeTranslation);

        if (print) {
            System.out.println("Starting the search..");
        }
        MotifFinder mf = new MotifFinder(network);
        long tijd = System.nanoTime();
        Set<MotifInstance> motifs = mf.findMotif(motif, false);
        tijd = System.nanoTime() - tijd;
        if (print) {
            System.out.println("Completed search in " + tijd / 1000000 + " milliseconds");
        }
        if (print) {
            System.out.println("Found " + motifs.size() + " instances of " + motifspec + " motif");
        }
        if (print) {
            System.out.println("Writing instances to file: " + output);
        }
        printMotifs(motifs, output);
        if (print) {
            System.out.println("Done.");
        }
        //            Set<MotifInstance> motifs=null;
        //            MotifFinder mf=null;
        //            System.out.println("Starting the search..");
        //            long tstart = System.nanoTime();
        //            for (int i = 0; i < it; i++) {
        //
        //                mf = new MotifFinder(network, allLinkTypes, true);
        //                motifs = mf.findMotif(motif);
        //            }
        //
        //            long tend = System.nanoTime();
        //            double time_in_ms = (tend - tstart) / 1000000.0;
        //            System.out.println("Found " + mf.totalFound + " motifs, " + time_in_ms + " ms");
        ////        System.out.println("Evaluated " + mf.totalNrMappedNodes+ " search nodes");
        ////        System.out.println("Found " + motifs.size() + " motifs, " + time_in_ms + " ms");
        //            printMotifs(motifs, output);

    }

}

From source file:com.cloud.test.utils.SubmitCert.java

public static void main(String[] args) {
    // Parameters
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    while (iter.hasNext()) {
        String arg = iter.next();

        if (arg.equals("-c")) {
            certFileName = iter.next();/*  w w  w  .j a  va2 s .c  o  m*/
        }

        if (arg.equals("-s")) {
            secretKey = iter.next();
        }

        if (arg.equals("-a")) {
            apiKey = iter.next();
        }

        if (arg.equals("-action")) {
            url = "Action=" + iter.next();
        }
    }

    Properties prop = new Properties();
    try {
        prop.load(new FileInputStream("conf/tool.properties"));
    } catch (IOException ex) {
        s_logger.error("Error reading from conf/tool.properties", ex);
        System.exit(2);
    }

    host = prop.getProperty("host");
    port = prop.getProperty("port");

    if (url.equals("Action=SetCertificate") && certFileName == null) {
        s_logger.error("Please set path to certificate (including file name) with -c option");
        System.exit(1);
    }

    if (secretKey == null) {
        s_logger.error("Please set secretkey  with -s option");
        System.exit(1);
    }

    if (apiKey == null) {
        s_logger.error("Please set apikey with -a option");
        System.exit(1);
    }

    if (host == null) {
        s_logger.error("Please set host in tool.properties file");
        System.exit(1);
    }

    if (port == null) {
        s_logger.error("Please set port in tool.properties file");
        System.exit(1);
    }

    TreeMap<String, String> param = new TreeMap<String, String>();

    String req = "GET\n" + host + ":" + prop.getProperty("port") + "\n/" + prop.getProperty("accesspoint")
            + "\n";
    String temp = "";

    if (certFileName != null) {
        cert = readCert(certFileName);
        param.put("cert", cert);
    }

    param.put("AWSAccessKeyId", apiKey);
    param.put("Expires", prop.getProperty("expires"));
    param.put("SignatureMethod", prop.getProperty("signaturemethod"));
    param.put("SignatureVersion", "2");
    param.put("Version", prop.getProperty("version"));

    StringTokenizer str1 = new StringTokenizer(url, "&");
    while (str1.hasMoreTokens()) {
        String newEl = str1.nextToken();
        StringTokenizer str2 = new StringTokenizer(newEl, "=");
        String name = str2.nextToken();
        String value = str2.nextToken();
        param.put(name, value);
    }

    //sort url hash map by key
    Set c = param.entrySet();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        Map.Entry me = (Map.Entry) it.next();
        String key = (String) me.getKey();
        String value = (String) me.getValue();
        try {
            temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&";
        } catch (Exception ex) {
            s_logger.error("Unable to set parameter " + value + " for the command " + param.get("command"), ex);
        }

    }
    temp = temp.substring(0, temp.length() - 1);
    String requestToSign = req + temp;
    String signature = UtilsForTest.signRequest(requestToSign, secretKey);
    String encodedSignature = "";
    try {
        encodedSignature = URLEncoder.encode(signature, "UTF-8");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    String url = "http://" + host + ":" + prop.getProperty("port") + "/" + prop.getProperty("accesspoint") + "?"
            + temp + "&Signature=" + encodedSignature;
    s_logger.info("Sending request with url:  " + url + "\n");
    sendRequest(url);
}