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:edu.smu.tspell.wordnet.impl.file.InflectionData.java

/**
 * Reads the exceptions from a single file that correspond to the
 * exceptions for a particular synset type.
 * //w w  w  .  j a va2  s  .co  m
 * @param  fileName Name of the file to read.
 * @param  type Syntactic type associated with the file.
 * @throws RetrievalException An error occurred reading the exception data.
 */
private void loadExceptions(String fileName, SynsetType type) throws IOException {
    StringTokenizer tokenizer;
    String inflection;
    String[] baseForms;

    String dir = PropertyNames.databaseDirectory;
    InputStream file = getClass().getResourceAsStream(dir + fileName);
    LineIterator iterator = IOUtils.lineIterator(file, null);
    //  Loop through all lines in the file
    while (iterator.hasNext()) {
        String line = iterator.nextLine();
        //  Parse the inflected word
        tokenizer = new StringTokenizer(line, WORD_DELIMITER);
        inflection = TextTranslator.translateToExternalFormat(tokenizer.nextToken());
        //  Get the inflected word's base forms
        baseForms = new String[tokenizer.countTokens()];
        for (int i = 0; i < baseForms.length; i++) {
            baseForms[i] = TextTranslator.translateToExternalFormat(tokenizer.nextToken());
        }
        //  Add an entry to the list for this word
        putMorphology(inflection, baseForms, type);
    }
    file.close();
}

From source file:org.alfresco.filesys.repo.CifsHelper.java

/**
 * Finds the nodes being reference by the given directory and file paths.
 * <p>//from w  ww  .j  av a  2 s  .c o  m
 * Examples of the path are:
 * <ul>
 *   <li>\New Folder\New Text Document.txt</li>
 *   <li>\New Folder\Sub Folder</li>
 * </ul>
 * 
 * @param pathRootNodeRef the node from which to start the path search
 * @param path the search path to either a folder or file
 * @return Returns references to all matching nodes
 */
public List<NodeRef> getNodeRefs(NodeRef pathRootNodeRef, String path) {
    // tokenize the path and push into a stack in reverse order so that
    // the root directory gets popped first
    StringTokenizer tokenizer = new StringTokenizer(path, FileName.DOS_SEPERATOR_STR, false);
    String[] tokens = new String[tokenizer.countTokens()];
    int count = 0;
    while (tokenizer.hasMoreTokens()) {
        tokens[count] = tokenizer.nextToken();
        count++;
    }
    Stack<String> pathElements = new Stack<String>();
    for (int i = tokens.length - 1; i >= 0; i--) {
        pathElements.push(tokens[i]);
    }

    // start with a single parent node
    List<NodeRef> pathRootNodeRefs = Collections.singletonList(pathRootNodeRef);

    // result storage
    List<NodeRef> results = new ArrayList<NodeRef>(5);
    List<NodeRef> rubeResults = new ArrayList<NodeRef>(5);

    // kick off the path walking
    addDescendents(pathRootNodeRefs, pathElements, rubeResults);

    for (NodeRef nodeRef : rubeResults) {
        QName nodeType = nodeService.getType(nodeRef);
        if (!excludedTypes.contains(nodeType)) {
            results.add(nodeRef);
        }
    }

    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved node references for path: \n" + "   path root: " + pathRootNodeRef + "\n"
                + "   path: " + path + "\n" + "   results: " + results);
    }
    return results;
}

From source file:edu.ucla.stat.SOCR.chart.SuperPieChart.java

public void setDataTable(String input) {

    StringTokenizer lnTkns = new StringTokenizer(input, "#");
    String line;//w  w w .  ja  v  a  2  s  . c om
    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++;
    }

    TableColumnModel columnModel = dataTable.getColumnModel();
    columnModel.getColumn(0).setHeaderValue("Name");
    columnModel.getColumn(1).setHeaderValue("Value");
    columnModel.getColumn(2).setHeaderValue("pullout flag");
    // this will update the mapping panel     
    resetTableColumns(dataTable.getColumnCount());
}

From source file:gov.nih.nci.cabig.caaers.web.admin.AgentImporter.java

/**
* This method accepts a String which should be like 
* "723227","(161-180)ESO-1 Peptide" //from   w ww  .j a  v a 2s.c om
* It splits the string into 2 tokens and creates a Agent object.
* If the number of token are less than 2 the record/line is rejected.
* @param agentString
* @param lineNumber
* @return
*/
protected DomainObjectImportOutcome<Agent> processAgent(String agentString, int lineNumber) {

    DomainObjectImportOutcome<Agent> agentImportOutcome = null;
    Agent agent = null;
    StringTokenizer st = null;
    String nscNumber;
    String agentName;

    if (StringUtils.isNotEmpty(agentString)) {

        logger.debug("Orginial line from file -- >>> " + agentString);
        agentString = agentString.trim();
        //Replace ", with "|
        //This is done to set a delimiter other than ,
        agentString = StringUtils.replace(agentString, "\",", "\"|");
        logger.debug("Modified line -- >>> " + agentString);
        //Generate tokens from input String.
        st = new StringTokenizer(agentString, "|");

        //If there are 2 tokens as expected, process the record. Create a Agent object.
        if (st.hasMoreTokens() && st.countTokens() == 2) {
            agentImportOutcome = new DomainObjectImportOutcome<Agent>();
            agent = new Agent();

            nscNumber = StringUtils.removeStart(st.nextToken(), "\"").trim();
            nscNumber = StringUtils.removeEnd(nscNumber, "\"");
            agentName = StringUtils.removeStart(st.nextToken(), "\"").trim();
            agentName = StringUtils.removeEnd(agentName, "\"");

            agent.setNscNumber(nscNumber);
            agent.setName(agentName);

            agentImportOutcome.setImportedDomainObject(agent);
            agentImportOutcome.setSavable(Boolean.TRUE);

        } else {
            logger.debug("Error in record -- >>> " + agentString);
            agentImportOutcome = new DomainObjectImportOutcome<Agent>();
            StringBuilder msgBuilder = new StringBuilder("Invalid agent record found at line ::: ");
            msgBuilder.append(lineNumber);
            agentImportOutcome.addErrorMessage(msgBuilder.toString(), Severity.ERROR);
        }
    }
    return agentImportOutcome;
}

From source file:com.l2jfree.gameserver.handler.admincommands.AdminEditChar.java

private void adminModifyCharacter(L2Player activeChar, String modifications) {
    L2Object target = activeChar.getTarget();

    if (!(target instanceof L2Player))
        return;/* ww  w.j a v  a2 s . c  o m*/

    L2Player player = (L2Player) target;
    StringTokenizer st = new StringTokenizer(modifications);

    if (st.countTokens() != 6) {
        editCharacter(player);
        return;
    }

    String hp = st.nextToken();
    String mp = st.nextToken();
    String cp = st.nextToken();
    String pvpflag = st.nextToken();
    String pvpkills = st.nextToken();
    String pkkills = st.nextToken();

    int hpval = Integer.parseInt(hp);
    int mpval = Integer.parseInt(mp);
    int cpval = Integer.parseInt(cp);
    int pvpflagval = Integer.parseInt(pvpflag);
    int pvpkillsval = Integer.parseInt(pvpkills);
    int pkkillsval = Integer.parseInt(pkkills);

    //Common character information
    player.sendMessage("Admin has changed your stats." + "  HP: " + hpval + "  MP: " + mpval + "  CP: " + cpval
            + "  PvP Flag: " + pvpflagval + " PvP/PK " + pvpkillsval + "/" + pkkillsval);
    player.getStatus().setCurrentHp(hpval);
    player.getStatus().setCurrentMp(mpval);
    player.getStatus().setCurrentCp(cpval);
    player.updatePvPFlag(pvpflagval);
    player.setPvpKills(pvpkillsval);
    player.setPkKills(pkkillsval);

    // Save the changed parameters to the database.
    player.store();

    StatusUpdate su = new StatusUpdate(player.getObjectId());
    su.addAttribute(StatusUpdate.CUR_HP, hpval);
    su.addAttribute(StatusUpdate.MAX_HP, player.getMaxHp());
    su.addAttribute(StatusUpdate.CUR_MP, mpval);
    su.addAttribute(StatusUpdate.MAX_MP, player.getMaxMp());
    su.addAttribute(StatusUpdate.CUR_CP, cpval);
    su.addAttribute(StatusUpdate.MAX_CP, player.getMaxCp());
    player.sendPacket(su);

    //Admin information
    player.sendMessage("Changed stats of " + player.getName() + "." + "  HP: " + hpval + "  MP: " + mpval
            + "  CP: " + cpval + "  PvP: " + pvpflagval + " / " + pvpkillsval);

    if (_log.isDebugEnabled())
        _log.debug("[GM]" + activeChar.getName() + " changed stats of " + player.getName() + ". " + " HP: "
                + hpval + " MP: " + mpval + " CP: " + cpval + " PvP: " + pvpflagval + " / " + pvpkillsval);

    showCharacterInfo(activeChar, null); //Back to start

    player.broadcastUserInfo();
    player.getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
    player.decayMe();
    player.spawnMe(activeChar.getX(), activeChar.getY(), activeChar.getZ());
}

From source file:com.appleframework.jmx.core.services.MBeanServiceImpl.java

/**
 * Map keys are of the format:/*w w w . j a  va  2  s .c o m*/
 * attr+<applicationId>+<attrName>
 *
 */
private List<ObjectAttribute> buildAttributeList(Map<String, String[]> attributes, ApplicationConfig appConfig,
        ObjectAttributeInfo[] objAttributes, ServerConnection connection, ObjectName objectName) {

    String applicationId = appConfig.getApplicationId();
    Iterator<String> it = attributes.keySet().iterator();
    List<ObjectAttribute> attributeList = new LinkedList<ObjectAttribute>();
    while (it.hasNext()) {
        String param = it.next();
        // look for keys which only start with "attr+"
        if (param.startsWith("attr+")) {
            StringTokenizer tokenizer = new StringTokenizer(param, "+");
            if (tokenizer.countTokens() != 3) {
                throw new RuntimeException("Invalid param name: " + param);
            }
            tokenizer.nextToken(); // equals to "attr"
            if (applicationId.equals(tokenizer.nextToken())) { // applicationId
                String attrName = tokenizer.nextToken();
                String attrType = getAttributeType(connection, objAttributes, attrName, objectName);

                String[] attrValues = attributes.get(param);
                Object typedValue = null;
                if (attrType.startsWith("[")) {
                    // it is an array
                    // the first elements in the array is dummy to allow
                    //  empty string to be saved
                    String[] actualValue = new String[attrValues.length - 1];
                    for (int i = 0; i < actualValue.length; i++) {
                        actualValue[i] = attrValues[i + 1];
                    }
                    try {
                        typedValue = ConvertUtils.convert(actualValue, Class.forName(attrType));
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    typedValue = getTypedValue(appConfig, attrValues[0], attrType);
                }
                attributeList.add(new ObjectAttribute(attrName, typedValue));
            }
        }
    }
    return attributeList;
}

From source file:org.alfresco.util.exec.RuntimeExec.java

/**
 * Supply a choice of commands to execute based on a mapping from the <i>os.name</i> system
 * property to the command to execute.  The {@link #KEY_OS_DEFAULT *} key can be used
 * to get a command where there is not direct match to the operating system key.
 * //from ww w  .j  a  va  2 s.  c o m
 * @param commandsByOS a map of command string keyed by operating system names
 * 
 * @deprecated          Use {@link #setCommandsAndArguments(Map)}
 */
public void setCommandMap(Map<String, String> commandsByOS) {
    // This is deprecated, so issue a warning
    logger.warn("The bean RuntimeExec property 'commandMap' has been deprecated;"
            + " use 'commandsAndArguments' instead.  See https://issues.alfresco.com/jira/browse/ETHREEOH-579.");
    Map<String, String[]> fixed = new LinkedHashMap<String, String[]>(7);
    for (Map.Entry<String, String> entry : commandsByOS.entrySet()) {
        String os = entry.getKey();
        String unparsedCmd = entry.getValue();
        StringTokenizer tokenizer = new StringTokenizer(unparsedCmd);
        String[] cmd = new String[tokenizer.countTokens()];
        for (int i = 0; i < cmd.length; i++) {
            cmd[i] = tokenizer.nextToken();
        }
        fixed.put(os, cmd);
    }
    setCommandsAndArguments(fixed);
}

From source file:com.softech.tbb.action.BaseAction.java

/**
 * Return array of tokens, using the result of <code>getTokeSep()</code>
 * as the separator. Blanks are trimmed from tokens.
 * /*  w  w w . j  a  v  a 2  s.  c om*/
 * @param parameter
 *            The string to tokenize into an array
 */
public String[] tokenize(String parameter) {

    // return ConvertUtils.tokensToArray(parameter,getTokenSep());

    StringTokenizer tokenizer = new StringTokenizer(parameter, getTokenSep());
    int i = 0;
    String[] tokens = new String[tokenizer.countTokens()];
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken().trim();
        if ((token == null) || (token.length() == 0))
            continue;
        tokens[i++] = token;
    }
    return tokens;
}

From source file:com.sshdemo.common.schedule.generate.quartz.JobsQuartzScheduler.java

protected String enumerateCronVals(String vals, int totalCount) throws BaseException {
    if (vals == null || vals.length() == 0) {
        logger.error("");
        throw new BaseException("", "");
    }//from   w  ww. j ava2  s  . c  o m
    StringTokenizer tokenizer = new StringTokenizer(vals, ",", false);
    if (tokenizer.countTokens() == totalCount) {
        return "*";
    } else {
        return vals;
    }
}

From source file:org.ardverk.daap.DaapRequest.java

/**
 * Sets and parses the URI. Note: if URIException is thrown then is this
 * Request in an inconsistent state!//  ww  w .j  a  v  a 2s . c o  m
 * 
 * @param uri
 * @throws URIException
 */
private void setURI(URI uri) throws URISyntaxException {

    this.uri = uri;

    if (uri != null) {

        String path = uri.getPath();

        this.queryMap = DaapUtil.parseQuery(uri.getQuery());

        if (path.equals("/server-info")) {
            requestType = SERVER_INFO;
        } else if (path.equals("/content-codes")) {
            requestType = CONTENT_CODES;
        } else if (path.equals("/login")) {
            requestType = LOGIN;
        } else if (path.equals("/logout")) {
            requestType = LOGOUT;
        } else if (path.equals("/update")) {
            requestType = UPDATE;
        } else if (path.equals("/resolve")) {
            requestType = RESOLVE;
        }

        if (queryMap.containsKey("session-id")) {
            sessionId = SessionId.parseSessionId(queryMap.get("session-id"));
        }

        if (!SessionId.INVALID.equals(sessionId)) {

            if (queryMap.containsKey("revision-number")) {
                revisionNumber = Integer.parseInt(queryMap.get("revision-number"));
            }

            if (queryMap.containsKey("delta")) {
                delta = Integer.parseInt(queryMap.get("delta"));
            }

            if (delta > revisionNumber) {
                throw new URISyntaxException(uri.toASCIIString(),
                        "Delta must be less or equal to revision-number: " + delta + "/" + revisionNumber);
            }

            if (queryMap.containsKey("meta")) {
                metaString = queryMap.get("meta");
            }

            isUpdateType = (delta != DaapUtil.NULL) && (delta < revisionNumber);

            // "/databases/id/items" 3 tokens
            // "/databases/id/containers" 3 tokens
            // "/databases/id/items/id.format" 4 tokens
            // "/databases/id/containers/id/items" 5 tokens
            if (path.equals("/databases")) {
                requestType = DATABASES;

            } else if (path.startsWith("/databases")) {

                StringTokenizer tok = new StringTokenizer(path, "/");
                int count = tok.countTokens();

                if (count >= 3) {
                    String token = tok.nextToken();

                    if (token.equals("databases") == false) {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " [" + token + "]@1");
                    }

                    databaseId = DaapUtil.parseUInt(tok.nextToken());
                    token = tok.nextToken();

                    if (token.equals("items")) {
                        requestType = DATABASE_SONGS;
                    } else if (token.equals("containers")) {
                        requestType = DATABASE_PLAYLISTS;
                    } else {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " [" + token + "]@2");
                    }

                    if (count == 3) {
                        // do nothing...

                    } else if (count == 4) {

                        token = tok.nextToken();

                        StringTokenizer fileTokenizer = new StringTokenizer(token, ".");

                        if (fileTokenizer.countTokens() == 2) {
                            itemId = DaapUtil.parseUInt(fileTokenizer.nextToken());
                            requestType = SONG;

                        } else {
                            throw new URISyntaxException(uri.toASCIIString(),
                                    "Unknown token in path: " + path + " [" + token + "]@3");
                        }

                    } else if (count == 5) {
                        containerId = DaapUtil.parseUInt(tok.nextToken());
                        token = tok.nextToken();

                        if (token.equals("items")) {
                            requestType = PLAYLIST_SONGS;

                        } else {
                            throw new URISyntaxException(uri.toASCIIString(),
                                    "Unknown token in path: " + path + " [" + token + "@4");
                        }

                    } else {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " [" + token + "]@5");
                    }
                } else {
                    throw new URISyntaxException(uri.toASCIIString(), "Unknown token in path: " + path);
                }
            }
        }

    } else {

        queryMap = null;
        metaString = null;
        isUpdateType = false;

        requestType = DaapUtil.NULL;
        databaseId = DaapUtil.NULL;
        containerId = DaapUtil.NULL;
        itemId = DaapUtil.NULL;

        sessionId = SessionId.INVALID;
        revisionNumber = DaapUtil.NULL;
        delta = DaapUtil.NULL;
    }
}