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, String delim) 

Source Link

Document

Constructs a string tokenizer for the specified string.

Usage

From source file:Main.java

/**
 * Tokenize the given String into a String array via a StringTokenizer.
 * <p>The given delimiters string is supposed to consist of any number of
 * delimiter characters. Each of those characters can be used to separate
 * tokens. A delimiter is always a single character; for multi-character
 * delimiters, consider using {@code delimitedListToStringArray}
 * @param str the String to tokenize/*from ww w  .j  a v a  2  s  .  c  om*/
 * @param delimiters the delimiter characters, assembled as String
 * (each of those characters is individually considered as delimiter)
 * @param trimTokens trim the tokens via String's {@code trim}
 * @param ignoreEmptyTokens omit empty tokens from the result array
 * (only applies to tokens that are empty after trimming; StringTokenizer
 * will not consider subsequent delimiters as token in the first place).
 * @return an array of the tokens ({@code null} if the input String
 * was {@code null})
 * @see java.util.StringTokenizer
 * @see String#trim()
 * @see #delimitedListToStringArray
 */
public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
        boolean ignoreEmptyTokens) {

    if (str == null) {
        return null;
    }
    StringTokenizer st = new StringTokenizer(str, delimiters);
    List<String> tokens = new ArrayList<>();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (trimTokens) {
            token = token.trim();
        }
        if (!ignoreEmptyTokens || token.length() > 0) {
            tokens.add(token);
        }
    }
    return toStringArray(tokens);
}

From source file:edu.lternet.pasta.common.EmlUtility.java

public static EmlPackageId emlPackageIdFromEML(File emlFile) throws Exception {
    EmlPackageId emlPackageId = null;/*from  www  . j a  v a2  s.  c  o m*/

    if (emlFile != null) {
        String emlString = FileUtils.readFileToString(emlFile);
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = documentBuilder.parse(IOUtils.toInputStream(emlString));
            emlPackageId = getEmlPackageId(document);
        }
        /*
         * If a parsing exception is thrown, attempt to parse the packageId
         * using regular expressions. This could be fooled by comments text
         * in the EML document but is still better than nothing at all.
         */
        catch (SAXException e) {
            StringTokenizer stringTokenizer = new StringTokenizer(emlString, "\n");
            String DOUBLE_QUOTE_PATTERN = "packageId=\"([^\"]*)\"";
            String SINGLE_QUOTE_PATTERN = "packageId='([^']*)'";
            Pattern doubleQuotePattern = Pattern.compile(DOUBLE_QUOTE_PATTERN);
            Pattern singleQuotePattern = Pattern.compile(SINGLE_QUOTE_PATTERN);
            while (stringTokenizer.hasMoreElements()) {
                String token = stringTokenizer.nextToken();
                if (token.contains("packageId")) {

                    Matcher doubleQuoteMatcher = doubleQuotePattern.matcher(token);
                    if (doubleQuoteMatcher.find()) {
                        String packageId = doubleQuoteMatcher.group(1);
                        System.out.println(packageId);
                        EmlPackageIdFormat formatter = new EmlPackageIdFormat(Delimiter.DOT);
                        emlPackageId = formatter.parse(packageId);
                        break;
                    }

                    Matcher singleQuoteMatcher = singleQuotePattern.matcher(token);
                    if (singleQuoteMatcher.find()) {
                        String packageId = singleQuoteMatcher.group(1);
                        EmlPackageIdFormat formatter = new EmlPackageIdFormat(Delimiter.DOT);
                        emlPackageId = formatter.parse(packageId);
                        break;
                    }

                }
            }
        }
    }

    return emlPackageId;
}

From source file:TreeUtil.java

public void addNode(String name, Object obj) {
    itsMap.put(name, obj);/*  w  w w .j  a  va2 s  .  c  o  m*/
    DefaultMutableTreeNode tempNode = itsRootNode;
    StringTokenizer tok = new StringTokenizer(name, ".");
    String currentName = null;
    while (tok.hasMoreTokens()) {
        String myTok = tok.nextToken();
        currentName = (currentName == null) ? myTok : currentName + "." + myTok;
        boolean createNew = true;
        for (int j = 0; j < tempNode.getChildCount(); j++) {
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) tempNode.getChildAt(j);
            if (childNode.toString().equals(myTok)) {
                tempNode = childNode;
                createNew = false;
                break;
            }
        }
        if (createNew) {
            DefaultMutableTreeNode aNode = new DefaultMutableTreeNode(myTok);
            itsTreeMap.put(currentName, aNode);
            // Let's give some consideration to where in the tree we place
            // the new node.
            // We want any nodes with children to be listed first, in
            // alphabetical order.
            // Then come nodes with no children, in alphabetical order.
            if (tok.hasMoreTokens()) {
                // This node is not a leaf node
                int targeti;
                for (targeti = 0; targeti < tempNode.getChildCount(); targeti++) {
                    TreeNode bNode = tempNode.getChildAt(targeti);
                    if (bNode.isLeaf() || bNode.toString().compareToIgnoreCase(myTok) > 0) {
                        break;
                    }
                }
                tempNode.insert(aNode, targeti);
            } else {
                // This node is a leaf node
                int targeti;
                for (targeti = 0; targeti < tempNode.getChildCount(); targeti++) {
                    TreeNode bNode = tempNode.getChildAt(targeti);
                    if (bNode.isLeaf() && bNode.toString().compareToIgnoreCase(myTok) > 0) {
                        break;
                    }
                }
                tempNode.insert(aNode, targeti);
            }
            tempNode = aNode;
        }
    }
}

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  ww  . j a  va 2 s  . 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:bioLockJ.util.MetadataUtil.java

/**
 * When a new column is added to metadata, this method will add the column, with all row values.
 * The updated file is output to the "outputDir" to be picked up by the next executor.
 * @param name//from w ww. ja  v  a2s .  c  om
 * @param map
 * @param fileDir
 * @throws Exception
 */
public static void addNumericColumn(final String name, final Map<String, Integer> map, final File fileDir)
        throws Exception {
    if (getAttributeNames().contains(name)) {
        Log.out.warn("Metadata already contains column [" + name + "] so this data will not be added to "
                + metadataFile.getName());
        return;
    }

    numericFields.add(name);

    final BufferedReader reader = new BufferedReader(new FileReader(metadataFile));
    metadataFile = new File(fileDir.getAbsolutePath() + File.separator + metadataFile.getName());
    final BufferedWriter writer = new BufferedWriter(new FileWriter(metadataFile));

    Log.out.info("Adding new attribute [" + name + "] to metadata");
    boolean isHeaderRow = true;
    try {
        final Set<String> keys = map.keySet();
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            final StringTokenizer st = new StringTokenizer(line, Constants.TAB_DELIM);
            if (isHeaderRow) {
                isHeaderRow = false;
                line += Constants.TAB_DELIM + name;
            } else {
                final String id = st.nextToken();
                if (keys.contains(id)) {
                    line += Constants.TAB_DELIM + map.get(id);
                } else {
                    line += Constants.TAB_DELIM + Config.requireString(Config.INPUT_NULL_VALUE);
                }
            }

            writer.write(line + Constants.RETURN);
        }
    } catch (final Exception ex) {
        Log.out.error("Error occurred updating metadata with new attribute [" + name + "]", ex);
    } finally {
        reader.close();
        writer.close();
        refresh();
    }
}

From source file:com.buaa.cfs.security.ShellBasedUnixGroupsMapping.java

/**
 * Get the current user's group list from Unix by running the command 'groups' NOTE. For non-existing user it will
 * return EMPTY list//from   w w w  .j  av  a2 s .co  m
 *
 * @param user user name
 *
 * @return the groups list that the <code>user</code> belongs to. The primary group is returned first.
 *
 * @throws IOException if encounter any error when running the command
 */
private static List<String> getUnixGroups(final String user) throws IOException {
    String result = "";
    try {
        result = Shell.execCommand(Shell.getGroupsForUserCommand(user));
    } catch (Shell.ExitCodeException e) {
        // if we didn't get the group - just return empty list;
        LOG.warn("got exception trying to get groups for user " + user + ": " + e.getMessage());
        return new LinkedList<String>();
    }

    StringTokenizer tokenizer = new StringTokenizer(result, Shell.TOKEN_SEPARATOR_REGEX);
    List<String> groups = new LinkedList<String>();
    while (tokenizer.hasMoreTokens()) {
        groups.add(tokenizer.nextToken());
    }

    // remove duplicated primary group
    if (!Shell.WINDOWS) {
        for (int i = 1; i < groups.size(); i++) {
            if (groups.get(i).equals(groups.get(0))) {
                groups.remove(i);
                break;
            }
        }
    }

    return groups;
}

From source file:com.liusoft.dlog4j.util.StringUtils.java

/**
 * ch//from  ww  w  . j a va2s. c om
 * @param tags
 * @param ch
 * @return
 */
public static List stringToList(String tags, String ch) {
    if (tags == null)
        return null;
    ArrayList tagList = new ArrayList();
    StringTokenizer st = new StringTokenizer(tags, ch);
    while (st.hasMoreElements()) {
        tagList.add(st.nextToken());
    }
    return tagList;
}

From source file:net.sourceforge.fenixedu.domain.phd.email.PhdEmailBean.java

public String getBccsView() {
    StringTokenizer tokenizer = new StringTokenizer(getBccs(), ",");
    StringBuilder result = new StringBuilder();
    int emailsCurrentLine = 0;
    while (tokenizer.hasMoreTokens()) {
        if (emailsCurrentLine == MAX_EMAILS_PER_LINE) {
            result.append('\n');
            emailsCurrentLine = 0;/*from  www  .j  av  a  2 s  .c  om*/
        }
        result.append(tokenizer.nextToken());
        result.append(',');
        emailsCurrentLine++;
    }
    if (!StringUtils.isEmpty(result.toString())) {
        result.deleteCharAt(result.length() - 1);
    }
    return result.toString();
}

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

@Override
public boolean useAdminCommand(String command, L2Player activeChar) {
    if (command.startsWith("admin_kill")) {
        StringTokenizer st = new StringTokenizer(command, " ");
        st.nextToken(); // skip command

        if (st.hasMoreTokens()) {
            String firstParam = st.nextToken();
            L2Player plyr = L2World.getInstance().getPlayer(firstParam);
            if (plyr != null) {
                if (st.hasMoreTokens()) {
                    try {
                        int radius = Integer.parseInt(st.nextToken());
                        for (L2Creature knownChar : plyr.getKnownList().getKnownCharactersInRadius(radius)) {
                            if (knownChar instanceof L2ControllableMobInstance || knownChar == activeChar)
                                continue;

                            kill(activeChar, knownChar);
                        }//from  w  ww. j  a va 2s  .co  m

                        activeChar.sendMessage("Killed all characters within a " + radius + " unit radius.");
                        return true;
                    } catch (NumberFormatException e) {
                        activeChar.sendMessage("Invalid radius.");
                        return false;
                    }
                }

                kill(activeChar, plyr);
            } else {
                try {
                    int radius = Integer.parseInt(firstParam);

                    for (L2Creature knownChar : activeChar.getKnownList().getKnownCharactersInRadius(radius)) {
                        if (knownChar instanceof L2ControllableMobInstance || knownChar == activeChar)
                            continue;

                        kill(activeChar, knownChar);
                    }

                    activeChar.sendMessage("Killed all characters within a " + radius + " unit radius.");
                    return true;
                } catch (NumberFormatException e) {
                    activeChar.sendMessage("Enter a valid player name or radius.");
                    return false;
                }
            }
        } else {
            L2Object obj = activeChar.getTarget();

            if (obj instanceof L2ControllableMobInstance || !(obj instanceof L2Creature)) {
                activeChar.sendPacket(SystemMessageId.INCORRECT_TARGET);
            } else {
                kill(activeChar, (L2Creature) obj);
            }
        }
    }

    return true;
}

From source file:fr.paris.lutece.plugins.updater.util.sql.SqlUtils.java

/**
 * Executes an SQL script/*from   ww  w  .ja  v a2  s. co  m*/
 * @param strScript An SQL script
 * @param plugin The plugin
 * @throws SQLException If an SQL exception occurs
 */
public static void executeSqlScript(String strScript, Plugin plugin) throws SQLException {
    String strCleanScript = strScript.substring(0, strScript.lastIndexOf(";"));
    StringTokenizer st = new StringTokenizer(strCleanScript, ";");

    Transaction transaction = new Transaction();

    try {
        while (st.hasMoreTokens()) {
            String strSQL = st.nextToken();
            transaction.prepareStatement(strSQL);
            transaction.executeStatement();
        }

        transaction.commit();
    } catch (SQLException ex) {
        transaction.rollback(ex);
        AppLogService.error("Execute SQL script error : " + ex.getMessage() + " - transaction rolled back.",
                ex);
        throw ex;
    }
}