Example usage for java.util StringTokenizer countTokens

List of usage examples for java.util StringTokenizer countTokens

Introduction

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

Prototype

public int countTokens() 

Source Link

Document

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Usage

From source file:Main.java

public static void main(String[] args) {
    int i = 0;/*ww w  .  jav  a 2 s  .  c  o  m*/
    String str = "one);two);three);four";
    StringTokenizer st = new StringTokenizer(str, ");");
    String temp[] = new String[st.countTokens()];

    while (st.hasMoreTokens()) {
        temp[i] = st.nextToken();
        System.out.println(temp[i]);
        i++;
    }
}

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.j  a  v  a 2 s  .  co m*/
}

From source file:LogStrTok.java

public static void main(String argv[]) {

    StringTokenizer matcher = new StringTokenizer(logEntryLine);

    System.out.println("tokens = " + matcher.countTokens());
    // StringTokenizer CAN NOT count if you are changing the delimiter!
    // if (matcher.countTokens() != NUM_FIELDS) {
    //    System.err.println("Bad log entry (or bug in StringTokenizer?):");
    //    System.err.println(logEntryLine);
    // }//ww  w  . j  av  a2s  .c o m

    System.out.println("Hostname: " + matcher.nextToken());
    // StringTokenizer makes you ask for tokens in order to skip them:
    matcher.nextToken(); // eat the "-"
    matcher.nextToken(); // again
    System.out.println("Date/Time: " + matcher.nextToken("]"));
    //matcher.nextToken(" "); // again
    System.out.println("Request: " + matcher.nextToken("\""));
    matcher.nextToken(" "); // again
    System.out.println("Response: " + matcher.nextToken());
    System.out.println("ByteCount: " + matcher.nextToken());
    System.out.println("Referer: " + matcher.nextToken("\""));
    matcher.nextToken(" "); // again
    System.out.println("User-Agent: " + matcher.nextToken("\""));
}

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 a 2  s.  c  o  m*/
    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:ReadTemp.java

/**
 * Method main/*ww w.  j ava 2 s .  c o m*/
 *
 *
 * @param args
 *
 * @throws OneWireException
 * @throws OneWireIOException
 *
 */
public static void main(String[] args) throws OneWireIOException, OneWireException {
    boolean usedefault = false;
    DSPortAdapter access = null;
    String adapter_name = null;
    String port_name = null;

    variableNames = new HashMap();

    if ((args == null) || (args.length < 1)) {
        try {
            access = OneWireAccessProvider.getDefaultAdapter();

            if (access == null)
                throw new Exception();
        } catch (Exception e) {
            System.out.println("Couldn't get default adapter!");
            printUsageString();

            return;
        }

        usedefault = true;
    }

    if (!usedefault) {
        StringTokenizer st = new StringTokenizer(args[0], "_");

        if (st.countTokens() != 2) {
            printUsageString();

            return;
        }

        adapter_name = st.nextToken();
        port_name = st.nextToken();

        System.out.println("Adapter Name: " + adapter_name);
        System.out.println("Port Name: " + port_name);
    }

    if (access == null) {
        try {
            access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
        } catch (Exception e) {
            System.out.println("That is not a valid adapter/port combination.");

            Enumeration en = OneWireAccessProvider.enumerateAllAdapters();

            while (en.hasMoreElements()) {
                DSPortAdapter temp = (DSPortAdapter) en.nextElement();

                System.out.println("Adapter: " + temp.getAdapterName());

                Enumeration f = temp.getPortNames();

                while (f.hasMoreElements()) {
                    System.out.println("   Port name : " + ((String) f.nextElement()));
                }
            }

            return;
        }
    }

    boolean scan = false;

    if (args.length > 1) {
        if (args[1].compareTo("--scan") == 0)
            scan = true;
    } else {
        populateVariableNames();
    }

    while (true) {
        access.adapterDetected();
        access.targetAllFamilies();
        access.beginExclusive(true);
        access.reset();
        access.setSearchAllDevices();

        boolean next = access.findFirstDevice();

        if (!next) {
            System.out.println("Could not find any iButtons!");

            return;
        }

        while (next) {
            OneWireContainer owc = access.getDeviceContainer();

            boolean isTempContainer = false;
            TemperatureContainer tc = null;

            try {
                tc = (TemperatureContainer) owc;
                isTempContainer = true;
            } catch (Exception e) {
                tc = null;
                isTempContainer = false; //just to reiterate
            }

            if (isTempContainer) {
                String id = owc.getAddressAsString();
                if (scan) {
                    System.out.println("= Temperature Sensor Found: " + id);
                } else {

                    double high = 0.0;
                    double low = 0.0;
                    byte[] state = tc.readDevice();

                    boolean selectable = tc.hasSelectableTemperatureResolution();

                    if (selectable)
                        try {
                            tc.setTemperatureResolution(0.0625, state);
                        } catch (Exception e) {
                            System.out.println("= Could not set resolution for " + id + ": " + e.toString());
                        }

                    try {
                        tc.writeDevice(state);
                    } catch (Exception e) {
                        System.out.println("= Could not write device state, all changes lost.");
                        System.out.println("= Exception occurred for " + id + ": " + e.toString());
                    }

                    boolean conversion = false;
                    try {
                        tc.doTemperatureConvert(state);
                        conversion = true;
                    } catch (Exception e) {
                        System.out.println("= Could not complete temperature conversion...");
                        System.out.println("= Exception occurred for " + id + ": " + e.toString());
                    }

                    if (conversion) {
                        state = tc.readDevice();

                        double temp = tc.getTemperature(state);
                        if (temp < 84) {
                            double temp_f = (9.0 / 5.0) * temp + 32;
                            setVariable(id, Double.toString(temp_f));
                        }
                        System.out.println("= Reported temperature from " + (String) variableNames.get(id) + "("
                                + id + "):" + temp);
                    }
                }
            }
            next = access.findNextDevice();
        }
        if (!scan) {
            try {
                Thread.sleep(60 * 5 * 1000);
            } catch (Exception e) {
            }
        } else {
            System.exit(0);
        }
    }
}

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

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

    try {/* w ww.  j  ava 2s .  co 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:com.glaf.base.modules.sys.service.mybatis.SysTreeServiceImpl.java

public static void main(String[] args) {
    String str1 = "1|2|5|195235|";
    String str2 = "1|2|5|195235|195274|195347|195483|";
    String tmp = str2.substring(str1.length(), str2.length());
    System.out.println(tmp);/*from w  w  w.  j a va  2 s. c o  m*/
    StringTokenizer token = new StringTokenizer(tmp, "|");
    System.out.println(token.countTokens());
}

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

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

    try {//  w  ww . j  a  v a2 s  . 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++;
        }
        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: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  w  w  w  .  jav  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.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(//w  ww . ja v  a 2s .c  om
                "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);
                }
            }
        }
    }
}