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:com.actionbarsherlock.sample.hcgallery.ContentFragment.java

boolean processDrop(DragEvent event, ImageView imageView) {
    // Attempt to parse clip data with expected format: category||entry_id.
    // Ignore event if data does not conform to this format.
    ClipData data = event.getClipData();
    if (data != null) {
        if (data.getItemCount() > 0) {
            Item item = data.getItemAt(0);
            String textData = (String) item.getText();
            if (textData != null) {
                StringTokenizer tokenizer = new StringTokenizer(textData, "||");
                if (tokenizer.countTokens() != 2) {
                    return false;
                }//from  ww w  .j a v  a 2 s  .  co m
                int category = -1;
                int entryId = -1;
                try {
                    category = Integer.parseInt(tokenizer.nextToken());
                    entryId = Integer.parseInt(tokenizer.nextToken());
                } catch (NumberFormatException exception) {
                    return false;
                }
                updateContentAndRecycleBitmap(category, entryId);
                // Update list fragment with selected entry.
                TitlesFragment titlesFrag = (TitlesFragment) getFragmentManager()
                        .findFragmentById(R.id.frag_title);
                titlesFrag.selectPosition(entryId);
                return true;
            }
        }
    }
    return false;
}

From source file:net.sf.l2j.gameserver.model.actor.instance.L2RebirthInstance.java

@Override
public void onBypassFeedback(L2PcInstance player, String command) {
    player.sendPacket(ActionFailed.STATIC_PACKET);
    StringTokenizer st = new StringTokenizer(command, " ");
    String actualCommand = st.nextToken();
    String val = "";
    if (st.countTokens() >= 1) {
        val = st.nextToken();
    }/*from w  w w. ja v a 2s  .  c  o  m*/
    if (actualCommand.equalsIgnoreCase("rebirth")) {
        setTarget(player);
        int lvl = player.getLevel();
        if (lvl >= 80) {
            if (val.equalsIgnoreCase("79")) {
                long delexp = 0;
                delexp = player.getStat().getExp() - player.getStat().getExpForLevel(lvl - 79);
                player.getStat().addExp(-delexp);
                player.broadcastKarma();
                player.sendMessage("Rebirth Accepted.");
                int itemReward = 1;
                player.addItem("Loot", Config.REBIRTH_ITEM, itemReward, player, true);
                player.sendMessage("You have win " + itemReward + " Rebirth Item");
            } else {
                NpcHtmlMessage html = new NpcHtmlMessage(1);
                html.setFile("data/html/mods/Rebirth/Rebirth.htm");
                html.replace("%lvl%", String.valueOf(player.getLevel()));
                sendHtmlMessage(player, html);
            }
        } else {
            player.sendMessage("You have to be at least level 80 to use Rebirth Engine.");
        }
        return;
    } else if (actualCommand.equalsIgnoreCase("Reward")) {
        setTarget(player);
        L2ItemInstance invItem = player.getInventory().getItemByItemId(Config.REBIRTH_ITEM);
        {
            if (invItem != null) {
                NpcHtmlMessage html = new NpcHtmlMessage(1);
                html.setFile("data/html/mods/Rebirth/reward.htm");
                html.replace("%lvl%", String.valueOf(player.getLevel()));
                sendHtmlMessage(player, html);
            } else {
                player.sendMessage("You Need Rebirth Book.");
            }
        }
    } else if (actualCommand.equalsIgnoreCase("skill1")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL1, Config.REBIRTH_SKILL1_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill2")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL2, Config.REBIRTH_SKILL2_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill3")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL3, Config.REBIRTH_SKILL3_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill4")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL4, Config.REBIRTH_SKILL4_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill5")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL5, Config.REBIRTH_SKILL5_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill6")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL6, Config.REBIRTH_SKILL6_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill7")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL7, Config.REBIRTH_SKILL7_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill8")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL8, Config.REBIRTH_SKILL8_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill9")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL9, Config.REBIRTH_SKILL9_LVL);
        player.addSkill(skill, true);
    } else if (actualCommand.equalsIgnoreCase("skill10")) {
        setTarget(player);
        player.destroyItem("Consume", Config.REBIRTH_ITEM, 1, null, false);
        L2Skill skill = SkillTable.getInstance().getInfo(Config.REBIRTH_SKILL10, Config.REBIRTH_SKILL10_LVL);
        player.addSkill(skill, true);
    } else {
        super.onBypassFeedback(player, command);
    }
}

From source file:edu.ucla.stat.SOCR.chart.demo.HistogramChartDemo5.java

public void setDataTable(String input) {
    hasExample = true;//from  ww w .  ja va  2  s.  c o  m
    StringTokenizer lnTkns = new StringTokenizer(input, "#");
    String line;
    int lineCt = lnTkns.countTokens();
    resetTableRows(lineCt);
    int r = 0;
    while (lnTkns.hasMoreTokens()) {
        line = lnTkns.nextToken();

        //   String tb[] =line.split("\t");
        StringTokenizer cellTkns = new StringTokenizer(line, " \t\f,");// IE use "space" Mac use tab as cell separator
        int cellCnt = cellTkns.countTokens();
        String tb[] = new String[cellCnt];
        int r1 = 0;
        while (cellTkns.hasMoreTokens()) {
            tb[r1] = cellTkns.nextToken();
            r1++;
        }
        //System.out.println("tb.length="+tb.length);
        int colCt = tb.length;
        resetTableColumns(colCt);
        for (int i = 0; i < tb.length; i++) {
            //System.out.println(tb[i]);
            if (tb[i].length() == 0)
                tb[i] = "0";
            dataTable.setValueAt(tb[i], r, i);
        }
        r++;
    }

    // this will update the mapping panel     
    resetTableColumns(dataTable.getColumnCount());
}

From source file:com.qframework.core.ObjectsFactory.java

private GameonModel.RefId refId(String name) {
    GameonModel.RefId refdata = new GameonModel.RefId();
    StringTokenizer tok = new StringTokenizer(name, ".");
    int count = tok.countTokens();
    if (count == 2) {

        refdata.name = tok.nextToken();//from w ww  . j a va  2s.  c o m
        String refid = tok.nextToken();
        refdata.id = Integer.parseInt(refid);
    } else if (count == 3) {
        refdata.name = tok.nextToken();
        tok.nextToken();
        // we only support iter
        refdata.alias = tok.nextToken();
        refdata.id = -1;
    } else {
        refdata.name = name;
        refdata.id = 0;
    }
    return refdata;
}

From source file:org.apache.catalina.cluster.tcp.ReplicationValve.java

public void setFilter(String filter) {
    log.debug("Loading request filters=" + filter);
    java.util.StringTokenizer t = new java.util.StringTokenizer(filter, ";");
    this.reqFilters = new java.util.regex.Pattern[t.countTokens()];
    int i = 0;//from   w w  w  .ja v a  2  s  .  com
    while (t.hasMoreTokens()) {
        String s = t.nextToken();
        log.debug("Request filter=" + s);
        try {
            reqFilters[i++] = java.util.regex.Pattern.compile(s);
        } catch (Exception x) {
            log.error("Unable to compile filter " + s, x);
        }
    }
}

From source file:eu.scape_project.tb.lsdr.seqfileutility.hadoop.HadoopJob.java

/**
 * Run hadoop job/*  w w w  .j a v  a 2 s .c  o m*/
 *
 * @param strings Command line arguments
 * @return Success indicator
 * @throws Exception
 */
@Override
public int run(String[] strings) throws Exception {
    try {
        String hdfsInputDir = null;
        FileSystem hdfs = FileSystem.get(conf);

        // hdfs input path is given as command parameter
        if (pc.getHdfsInputPath() != null) {
            hdfsInputDir = pc.getHdfsInputPath();
            // hdfs input file is created
        } else {
            hdfsInputDir = "input/" + System.currentTimeMillis() + "sfu/";

            String[] extensions = null;
            if (pc.getExtStr() != null) {
                StringTokenizer st = new StringTokenizer(pc.getExtStr(), ",");
                extensions = new String[st.countTokens()];
                int i = 0;
                while (st.hasMoreTokens()) {
                    extensions[i] = st.nextToken();
                    i++;
                }
            }

            hdfs.mkdirs(new Path(hdfsInputDir));

            String hdfsIinputPath = hdfsInputDir + "inputpaths.txt";
            Path path = new Path(hdfsIinputPath);

            FSDataOutputStream outputStream = hdfs.create(path);

            List<String> dirs = StringUtils.getStringListFromString(pc.getDirsStr(), ",");
            for (String dir : dirs) {
                File directory = new File(dir);
                if (directory.isDirectory()) {
                    // Alternatively, the java traverse method can be used
                    // for creating the file paths:
                    //traverse(directory, outputStream);
                    writeFilePaths(directory, outputStream);
                } else {
                    logger.warn("Parameter \"" + dir + "\" is not a directory " + "(skipped)");
                }
            }
            outputStream.close();
            if (hdfs.exists(path)) {
                logger.info(
                        "Input paths created in \"" + hdfs.getHomeDirectory() + "/" + path.toString() + "\"");
            } else {
                logger.error("Input paths have not been created in hdfs.");
                return 1;
            }
        }
        String hadoopJobName = "Hadoop_sequence_file_creation";
        if (pc.getHadoopJobName() != null && !pc.getHadoopJobName().equals(""))
            hadoopJobName = pc.getHadoopJobName();
        Job job = new Job(conf, hadoopJobName);

        job.setJarByClass(SequenceFileUtility.class);
        job.setMapperClass(SmallFilesSequenceFileMapper.class);
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(BytesWritable.class);
        job.setOutputFormatClass(SequenceFileOutputFormat.class);
        TextInputFormat.addInputPath(job, new Path(hdfsInputDir));

        String hdfsOutputDir = "output/" + System.currentTimeMillis() + "sfu/";

        SequenceFileOutputFormat.setOutputPath(job, new Path(hdfsOutputDir));
        SequenceFileOutputFormat.setOutputCompressionType(job, CompressionType.get(pc.getCompressionType()));

        int success = job.waitForCompletion(true) ? 0 : 1;
        boolean seqFileExists = hdfs.exists(new Path(hdfsOutputDir + "part-r-00000"));
        if (success == 0 && seqFileExists) {
            logger.info("Sequence file created: \"" + hdfs.getHomeDirectory() + "/" + hdfsOutputDir
                    + "part-r-00000" + "\"");
            pc.setOutputDirectory(hdfsOutputDir);
            return 0;
        } else {
            logger.error("Sequence file not created in hdfs");
            return 1;
        }
    } catch (Exception e) {
        logger.error("IOException occurred", e);
    } finally {
    }
    return 0;
}

From source file:org.alfresco.web.ui.repo.component.template.UITemplate.java

/**
 * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext)
 */// w  w w. java 2  s  .  c  o m
public void encodeBegin(FacesContext context) throws IOException {
    if (isRendered() == false) {
        return;
    }

    // get the template to process
    String templateRef = getTemplate();
    if (templateRef == null || templateRef.length() == 0) {
        // no noderef/classpath template found - try a name based path
        String path = getTemplatePath();
        if (path != null && path.length() != 0) {
            // convert cm:name based path to a NodeRef
            StringTokenizer t = new StringTokenizer(path, "/");
            int tokenCount = t.countTokens();
            String[] elements = new String[tokenCount];
            for (int i = 0; i < tokenCount; i++) {
                elements[i] = t.nextToken();
            }
            NodeRef pathRef = BaseServlet.resolveWebDAVPath(context, elements, false);
            if (pathRef != null) {
                templateRef = pathRef.toString();
            }
        }
    }

    if (templateRef != null && templateRef.length() != 0) {
        long startTime = 0;
        if (logger.isDebugEnabled()) {
            logger.debug("Using template processor");
            startTime = System.currentTimeMillis();
        }

        // get the data model to use - building default FreeMarker model as required
        Object model = getTemplateModel(getModel(), templateRef);

        // process the template against the model
        try {
            TemplateService templateService = Repository.getServiceRegistry(context).getTemplateService();
            templateService.processTemplate(templateRef, model, context.getResponseWriter());
        } catch (TemplateException err) {
            Utils.addErrorMessage(err.getMessage(), err);
        }

        if (logger.isDebugEnabled()) {
            long endTime = System.currentTimeMillis();
            logger.debug("Time to process template: " + (endTime - startTime) + "ms");
        }
    }
}

From source file:org.apache.axis.wsdl.toJava.Utils.java

/**
 * Method makePackageName//from   ww  w.ja v  a  2s  . com
 *
 * @param namespace
 * @return
 */
public static String makePackageName(String namespace) {

    String hostname = null;
    String path = "";

    // get the target namespace of the document
    try {
        URL u = new URL(namespace);

        hostname = u.getHost();
        path = u.getPath();
    } catch (MalformedURLException e) {
        if (namespace.indexOf(":") > -1) {
            hostname = namespace.substring(namespace.indexOf(":") + 1);

            if (hostname.indexOf("/") > -1) {
                hostname = hostname.substring(0, hostname.indexOf("/"));
            }
        } else {
            hostname = namespace;
        }
    }

    // if we didn't file a hostname, bail
    if (hostname == null) {
        return null;
    }

    // convert illegal java identifier
    hostname = hostname.replace('-', '_');
    path = path.replace('-', '_');

    // chomp off last forward slash in path, if necessary
    if ((path.length() > 0) && (path.charAt(path.length() - 1) == '/')) {
        path = path.substring(0, path.length() - 1);
    }

    // tokenize the hostname and reverse it
    StringTokenizer st = new StringTokenizer(hostname, ".:");
    String[] words = new String[st.countTokens()];

    for (int i = 0; i < words.length; ++i) {
        words[i] = st.nextToken();
    }

    StringBuffer sb = new StringBuffer(namespace.length());

    for (int i = words.length - 1; i >= 0; --i) {
        addWordToPackageBuffer(sb, words[i], (i == words.length - 1));
    }

    // tokenize the path
    StringTokenizer st2 = new StringTokenizer(path, "/");

    while (st2.hasMoreTokens()) {
        addWordToPackageBuffer(sb, st2.nextToken(), false);
    }

    return sb.toString();
}

From source file:hudson.plugins.testlink.result.TestCaseWrapper.java

/**
 * Splits a String by comma and gets an array of Strings.
 *//*w w  w . j  a va2 s  . c  o  m*/
protected String[] split(String input) {
    if (StringUtils.isBlank(input)) {
        return new String[0];
    }

    StringTokenizer tokenizer = new StringTokenizer(input, ",");

    String[] values = new String[tokenizer.countTokens()];

    for (int i = 0; tokenizer.hasMoreTokens(); i++) {
        values[i] = tokenizer.nextToken().trim();
    }

    return values;
}

From source file:org.pdfgal.pdfgalweb.validators.utils.impl.ValidatorUtilsImpl.java

/**
 * This method represents the loop for the validateConcretePages method.
 * //w ww.  j a v a 2 s. c  o  m
 * @param totalPages
 * @param pages
 * @param delim1
 * @param delim2
 * @param moreThanOne
 * @return
 */
private boolean validateConcretePagesLoop(final Integer totalPages, final String pages, final String delim1,
        final String delim2, final boolean testMoreThanOne) {

    boolean result = false;

    if (totalPages != null && StringUtils.isNotEmpty(pages) && StringUtils.isNotEmpty(delim1)) {

        result = true;

        final StringTokenizer st = new StringTokenizer(pages, delim1);
        Integer previous = null;
        String token = null;
        if ("-".equals(delim1) && st.countTokens() != 2) {
            result = false;
        } else {
            while (st.hasMoreElements()) {
                try {
                    token = st.nextToken();
                    final Integer current = Integer.valueOf(token);
                    boolean isMoreThan = true;
                    if (testMoreThanOne) {
                        isMoreThan = (current.compareTo(new Integer(2)) < 0);
                    } else {
                        isMoreThan = (current.compareTo(new Integer(1)) < 0);
                    }
                    if ((current.compareTo(totalPages) > 0) || isMoreThan
                            || (previous != null && current.compareTo(previous) <= 0)) {
                        result = false;
                        break;
                    }
                    previous = current;

                } catch (final Exception e) {
                    if (StringUtils.isNotEmpty(delim2)) {
                        result = this.validateConcretePagesLoop(totalPages, token, delim2, null,
                                testMoreThanOne);

                    } else {
                        result = false;
                    }

                    if (!result) {
                        break;
                    }
                }
            }
        }
    }

    return result;
}