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.chinamobile.bcbsp.examples.connectedcomponent.CCVertexLiteNew.java

@Override
public void fromString(String vertexData) throws Exception {
    String[] buffer = new String[2];
    StringTokenizer str = new StringTokenizer(vertexData, Constants.KV_SPLIT_FLAG);
    if (str.hasMoreElements()) {
        buffer[0] = str.nextToken();// www. ja  v  a  2s.  c om
    } else {
        throw new Exception();
    }
    if (str.hasMoreElements()) {
        buffer[1] = str.nextToken();
    }
    str = new StringTokenizer(buffer[0], Constants.SPLIT_FLAG);
    if (str.countTokens() != 2) {
        throw new Exception();
    }
    this.vertexID = Integer.valueOf(str.nextToken());
    float tmp = Float.valueOf(str.nextToken());
    this.vertexValue = (int) tmp;

    if (buffer[1].length() > 0) { // There has edges.
        str = new StringTokenizer(buffer[1], Constants.SPACE_SPLIT_FLAG);
        while (str.hasMoreTokens()) {
            CCEdgeLiteNew edge = new CCEdgeLiteNew();
            edge.fromString(str.nextToken());
            this.edgesList.add(edge);
        }
    }
}

From source file:org.alfresco.rest.framework.tools.RecognizedParamsExtractor.java

/**
 * Takes the web request and looks for a "fields" parameter (otherwise deprecated "properties" parameter).
 * Parses the parameter and produces a list of bean properties to use as a filter A
 * SimpleBeanPropertyFilter it returned that uses the bean properties. If no
 * filter param is set then a default BeanFilter is returned that will never
 * filter fields (ie. Returns all bean properties).
 * If selectList is provided then it will take precedence (ie. be included) over the fields/properties filter
 * for top-level entries (bean properties).
 * For example, this will return entries from both select & properties, eg.
 * select=abc,def&properties=id,name,ghi
 * Note: it should be noted that API-generic "fields" clause does not currently work for sub-entries.
 * Hence, even if the API-specific "select" clause allows selection of a sub-entries this cannot be used
 * with "fields" filtering. For example, an API-specific method may implement and return "abc/blah", eg.
 * select=abc/blah//from  w w w  . j a v  a 2 s .  c  om
 * However the following will not return "abc/blah" if used with fields filtering, eg.
 * select=abc/blah&fields=id,name,ghi
 * If fields filtering is desired then it would require "abc" to be selected and returned as a whole, eg.
 * select=abc&fields=id,name,ghi
 *
 * @param filterParams
 * @param selectList
 * @return
 */
default BeanPropertiesFilter getFilter(String filterParams, List<String> selectList) {
    if (filterParams != null) {
        StringTokenizer st = new StringTokenizer(filterParams, ",");
        Set<String> filteredProperties = new HashSet<String>(st.countTokens());
        while (st.hasMoreTokens()) {
            filteredProperties.add(st.nextToken());
        }

        // if supplied, the select takes precedence over the filter (fields/properties) for top-level bean properties
        if (selectList != null) {
            for (String select : selectList) {
                String[] split = select.split("/");
                filteredProperties.add(split[0]);
            }
        }

        rpeLogger().debug("Filtering using the following properties: " + filteredProperties);
        BeanPropertiesFilter filter = new BeanPropertiesFilter(filteredProperties);
        return filter;
    }
    return BeanPropertiesFilter.ALLOW_ALL;
}

From source file:com.sun.faban.harness.webclient.Uploader.java

/**
 * Updates the tags file.//w  w  w.ja v a 2  s.c  o  m
 * @param req
 * @param resp
 * @throws java.io.IOException
 */
public void updateTagsFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String tags = req.getParameter("tags");
    String runId = req.getParameter("runId");
    RunResult result = RunResult.getInstance(new RunId(runId));
    StringBuilder formattedTags = new StringBuilder();
    File runTagFile = new File(Config.OUT_DIR + runId + "/META-INF/tags");
    if (tags != null && !"".equals(tags)) {
        StringTokenizer t = new StringTokenizer(tags, " \n,");
        ArrayList<String> tagList = new ArrayList<String>(t.countTokens());
        while (t.hasMoreTokens()) {
            String nextT = t.nextToken().trim();
            if (nextT != null && !"".equals(nextT)) {
                formattedTags.append(nextT + "\n");
                tagList.add(nextT);
            }
        }
        FileHelper.writeContentToFile(formattedTags.toString(), runTagFile);
        result.tags = tagList.toArray(new String[tagList.size()]);
    }
    try {
        uploadTags(runId);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Uploader.class.getName()).log(Level.SEVERE, null, ex);
    }
    Writer w = resp.getWriter();
    w.write("Tags updating completed");
    w.flush();
    w.close();
}

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

public void setDataTable(String input) {
    hasExample = true;//  w  ww .ja  v  a 2 s .  c om
    StringTokenizer lnTkns = new StringTokenizer(input, "#");
    String line;
    int colCt = lnTkns.countTokens();
    resetTableColumns(colCt * 2);
    int r = 0;
    while (lnTkns.hasMoreTokens()) {
        line = lnTkns.nextToken();

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

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

From source file:org.yes.cart.payment.impl.PayPalExpressCheckoutPaymentGatewayImpl.java

/**
 * ******************************************************************************
 * deformatNVP: Function to break the NVP string into a HashMap
 * pPayLoad is the NVP string./*from  w  w w  .  j  a  v  a 2 s .  co m*/
 * returns a HashMap object containing all the name value pairs of the string.
 * *******************************************************************************
 *
 * @param pPayload given string
 * @return map
 */
public Map<String, String> deformatNVP(final String pPayload) {
    Map<String, String> nvp = new HashMap<String, String>();
    StringTokenizer stTok = new StringTokenizer(pPayload, AND);
    while (stTok.hasMoreTokens()) {
        StringTokenizer stInternalTokenizer = new StringTokenizer(stTok.nextToken(), EQ);
        if (stInternalTokenizer.countTokens() == 2) {
            try {
                String key = URLDecoder.decode(stInternalTokenizer.nextToken(), "UTF-8");
                String value = URLDecoder.decode(stInternalTokenizer.nextToken(), "UTF-8");
                nvp.put(key.toUpperCase(), value);
            } catch (UnsupportedEncodingException e) {
                ShopCodeContext.getLog(this).error("Unable to decode NVP payload " + pPayload, e);
            }
        }
    }
    return nvp;
}

From source file:com.bigdata.dastor.db.ColumnFamilyStore.java

public static int getGenerationFromFileName(String filename) {
    /*//from   ww w .  ja va 2  s  . c o m
     * File name is of the form <table>-<column family>-<index>-Data.db.
     * This tokenizer will strip the .db portion.
     */
    StringTokenizer st = new StringTokenizer(filename, "-");
    /*
     * Now I want to get the index portion of the filename. We accumulate
     * the indices and then sort them to get the max index.
     */
    int count = st.countTokens();
    int i = 0;
    String index = null;
    while (st.hasMoreElements()) {
        index = (String) st.nextElement();
        if (i == (count - 2)) {
            break;
        }
        ++i;
    }
    return Integer.parseInt(index);
}

From source file:org.alfresco.rest.framework.tools.RecognizedParamsExtractor.java

/**
 * Takes the Sort parameter as a String and parses it into a List of SortColumn objects.
 * The format is a comma seperated list of "columnName sortDirection",
 * e.g. "name DESC, age ASC".  It is not case sensitive and the sort direction is optional
 * It default to sort ASCENDING./*from   w  w w.j av a2s.co  m*/
 *
 * @param sortParams - String passed in on the request
 * @return - the sort columns or an empty list if the params were invalid.
 */
default List<SortColumn> getSort(String sortParams) {
    if (sortParams != null) {
        StringTokenizer st = new StringTokenizer(sortParams, ",");
        List<SortColumn> sortedColumns = new ArrayList<SortColumn>(st.countTokens());
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            StringTokenizer columnDesc = new StringTokenizer(token, " ");
            if (columnDesc.countTokens() <= 2) {
                String columnName = columnDesc.nextToken();
                String sortOrder = SortColumn.ASCENDING;
                if (columnDesc.hasMoreTokens()) {
                    String sortDef = columnDesc.nextToken().toUpperCase();
                    if (SortColumn.ASCENDING.equals(sortDef) || SortColumn.DESCENDING.equals(sortDef)) {
                        sortOrder = sortDef;
                    } else {
                        rpeLogger().debug("Invalid sort order definition (" + sortDef + ").  Valid values are "
                                + SortColumn.ASCENDING + " or " + SortColumn.DESCENDING + ".");
                    }
                }
                sortedColumns.add(new SortColumn(columnName, SortColumn.ASCENDING.equals(sortOrder)));
            }
            // filteredProperties.add();
        }
        //            logger.debug("Filtering using the following properties: " + filteredProperties);
        //            BeanPropertiesFilter filter = new BeanPropertiesFilter(filteredProperties);
        return sortedColumns;
    }
    return Collections.emptyList();
}

From source file:edu.stanford.muse.util.EmailUtils.java

/** get a list of possible names, like "First Last" from "First.Last@gmail.com" etc */
public static List<String> parsePossibleNamesFromEmailAddress(String email) {
    List<String> result = new ArrayList<String>();
    if (email == null)
        return result;
    String strippedEmail = getAccountNameFromEmailAddress(email);

    // handle addrs like mondy_dana%umich-mts.mailnet@mit-multics.arp, in this case strip out the part after %
    int idx = strippedEmail.indexOf("%");
    if (idx >= 0)
        strippedEmail = strippedEmail.substring(0, idx);

    // 2 sets of splitters, one containing just periods, other just underscores.
    // most people have periods, but at least Dell has underscores
    String[] splitters = new String[] { ".", "_" };
    for (String splitter : splitters) {
        StringTokenizer st = new StringTokenizer(strippedEmail, splitter);
        int nTokens = st.countTokens();
        // allow only first.last or first.middle.last
        if (nTokens < 2 || nTokens > 3)
            continue;

        String possibleName = "";
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (Util.hasOnlyDigits(token))
                return result; // abort immediately if only numbers, we don't want things like 70451.2444@compuserve.com
            possibleName += Util.capitalizeFirstLetter(token) + " "; // optionally we could upper case first letter of each token.
        }//from w  ww. j av a2 s .  co  m
        possibleName = possibleName.trim(); // remove trailing space
        result.add(possibleName);
    }
    return result;
}

From source file:egovframework.com.utl.sys.fsm.service.FileSystemUtils.java

/**
 * Find free space on the *nix platform using the 'df' command.
 *
 * @param path  the path to get free space for
 * @param kb  whether to normalize to kilobytes
 * @param posix  whether to use the posix standard format flag
 * @return the amount of free drive space on the volume
 * @throws IOException if an error occurs
 *///from   w  w  w .j av a2  s . com
long freeSpaceUnix(String path, boolean kb, boolean posix) throws IOException {
    if (path.length() == 0) {
        throw new IllegalArgumentException("Path must not be empty");
    }
    path = FilenameUtils.normalize(path);

    String osName = System.getProperty("os.name");

    // build and run the 'dir' command
    String flags = "-";
    if (kb && osName.indexOf("hp-ux") == -1) {
        flags += "k";
    }
    if (posix && osName.indexOf("hp-ux") == -1) {
        flags += "P";
    }

    String dfCommand = "df";

    if (osName.indexOf("hp-ux") != -1) {
        dfCommand = "bdf";
    }

    String[] cmdAttribs = (flags.length() > 1 ? new String[] { dfCommand, flags, path }
            : new String[] { dfCommand, path });

    // perform the command, asking for up to 3 lines (header, interesting, overflow)
    List lines = performCommand(cmdAttribs, 3);
    if (lines.size() < 2) {
        // unknown problem, throw exception
        throw new IOException("Command line 'df' did not return info as expected " + "for path '" + path
                + "'- response was " + lines);
    }
    String line2 = (String) lines.get(1); // the line we're interested in

    // Now, we tokenize the string. The fourth element is what we want.
    StringTokenizer tok = new StringTokenizer(line2, " ");
    if (tok.countTokens() < 4) {
        // could be long Filesystem, thus data on third line
        if (tok.countTokens() == 1 && lines.size() >= 3) {
            String line3 = (String) lines.get(2); // the line may be interested in
            tok = new StringTokenizer(line3, " ");
        } else {
            throw new IOException("Command line 'df' did not return data as expected " + "for path '" + path
                    + "'- check path is valid");
        }
    } else {
        tok.nextToken(); // Ignore Filesystem
    }
    tok.nextToken(); // Ignore 1K-blocks
    tok.nextToken(); // Ignore Used
    String freeSpace = tok.nextToken();
    return parseBytes(freeSpace, path);
}

From source file:com.hypersocket.netty.HttpRequestServletWrapper.java

@Override
public Cookie[] getCookies() {
    if (cookies == null && getHeader("COOKIE") != null) {
        String tmp = getHeader("COOKIE");
        StringTokenizer t = new StringTokenizer(tmp, ";");
        cookies = new Cookie[t.countTokens()];
        int count = 0;
        while (t.hasMoreTokens()) {
            String nextCookie = t.nextToken().trim();
            int equalsPos = nextCookie.indexOf('=');
            String cookieName = nextCookie.substring(0, equalsPos);
            String cookieValue = nextCookie.substring(equalsPos + 1);
            cookies[count++] = new Cookie(cookieName, cookieValue);
        }/*from   w  ww.  j a va2 s.  co  m*/
    } else if (cookies == null) {
        cookies = new Cookie[0];
    }
    return cookies;
}