Example usage for java.util StringTokenizer hasMoreTokens

List of usage examples for java.util StringTokenizer hasMoreTokens

Introduction

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

Prototype

public boolean hasMoreTokens() 

Source Link

Document

Tests if there are more tokens available from this tokenizer's string.

Usage

From source file:com.openkm.dao.ConfigDAO.java

/**
 * Find by pk with a default value//from w  ww. ja va2  s  . c  o  m
 */
public static List<String> getList(String key, String defaultValue) throws DatabaseException {
    List<String> list = new ArrayList<String>();
    String dbValue = getProperty(key, defaultValue, Config.LIST);
    StringTokenizer st = new StringTokenizer(dbValue, "\t\n\r\f");

    while (st.hasMoreTokens()) {
        String tk = st.nextToken().trim();

        if (tk != null && !tk.equals("")) {
            list.add(tk);
        }
    }

    return list;
}

From source file:Main.java

/**
 * Given an {@link NNTPClient} instance, and an integer range of messages, return 
 * an array of {@link Article} instances.
 * @param client //from w ww .j  a v a 2s.  co  m
 * @param lowArticleNumber
 * @param highArticleNumber
 * @return Article[] An array of Article
 * @throws IOException
 */
public static Article[] getArticleInfo(NNTPClient client, int lowArticleNumber, int highArticleNumber)
        throws IOException {
    Reader reader = null;
    Article[] articles = null;
    reader = (DotTerminatedMessageReader) client.retrieveArticleInfo(lowArticleNumber, highArticleNumber);

    if (reader != null) {
        String theInfo = readerToString(reader);
        StringTokenizer st = new StringTokenizer(theInfo, "\n");

        // Extract the article information
        // Mandatory format (from NNTP RFC 2980) is :
        // Subject\tAuthor\tDate\tID\tReference(s)\tByte Count\tLine Count

        int count = st.countTokens();
        articles = new Article[count];
        int index = 0;

        while (st.hasMoreTokens()) {
            StringTokenizer stt = new StringTokenizer(st.nextToken(), "\t");
            Article article = new Article();
            article.setArticleNumber(Integer.parseInt(stt.nextToken()));
            article.setSubject(stt.nextToken());
            article.setFrom(stt.nextToken());
            article.setDate(stt.nextToken());
            article.setArticleId(stt.nextToken());
            article.addHeaderField("References", stt.nextToken());
            articles[index++] = article;
        }
    } else {
        return null;
    }

    return articles;
}

From source file:de.instantouch.model.io.SnakeJSONWriter.java

public static String beautify(String jsonString, boolean appendNewline) {

    String beautyString = appendNewline ? newliner(jsonString) : jsonString;

    String delim = String.valueOf("\r\n");
    StringTokenizer tokenizer = new StringTokenizer(beautyString, delim);

    StringWriter beautyWriter = new StringWriter();
    PrintWriter beautyPrinter = new PrintWriter(beautyWriter);

    int tabs = 0;
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if (token.contains("}") || token.contains("]")) {
            tabs--;/*from  w ww  .  ja  va  2s  .c o  m*/
        }

        beautyPrinter.println(printtabs(beautyPrinter, tabs) + token);
        if (token.contains("{") || token.contains("[")) {
            tabs++;
        }
    }

    return beautyWriter.toString();
}

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

private static Triple<Integer, Integer, Integer> parseDate(String s) {
    // separate into month and date
    // "jan10", "10jan", "jan 10" "10 jan" should all work
    s = s.toLowerCase();// w w w.  j  a  v a2  s .com
    s = s.trim();
    StringBuilder sb = new StringBuilder();
    // detect when string changes from alpha to num or vice versa and ensure a whitespace there
    boolean prevCharDigit = false, prevCharLetter = false;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (Character.isWhitespace(c)) {
            sb.append(c);
            prevCharDigit = prevCharLetter = false;
            continue;
        }
        // treat apostrophe like a space
        if (c == '\'') {
            sb.append(' ');
            prevCharDigit = prevCharLetter = false;
            continue;
        }

        if (Character.isLetter(c)) {
            if (prevCharDigit)
                sb.append(' ');
            sb.append(c);
            prevCharLetter = true;
            prevCharDigit = false;
        } else if (Character.isDigit(c)) {
            if (prevCharLetter)
                sb.append(' ');
            sb.append(c);
            prevCharDigit = true;
            prevCharLetter = false;
        } else
            throw new RuntimeException();
    }

    String newS = sb.toString();
    log.info("string " + s + " parsed to " + newS);
    StringTokenizer st = new StringTokenizer(newS);

    int nTokens = st.countTokens();
    if (nTokens == 0 || nTokens > 3)
        return new Triple<Integer, Integer, Integer>(-1, -1, -1);

    int mm = -1, dd = -1, yy = -1;
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        boolean isNumber = true;
        int num = -1;
        try {
            num = Integer.parseInt(token);
        } catch (NumberFormatException nfe) {
            isNumber = false;
        }
        if (isNumber && num < 0)
            return new Triple<Integer, Integer, Integer>(-1, -1, -1);
        if (isNumber) {
            if (dd == -1 && num > 0 && num <= 31)
                dd = num;
            else if (yy == -1) {
                yy = num;
                if (yy < 100) {
                    yy = (yy > 12) ? (1900 + yy) : (2000 + yy);
                }
                if (yy < 1900 || yy > 2015)
                    return new Triple<Integer, Integer, Integer>(-1, -1, -1);
            } else
                return new Triple<Integer, Integer, Integer>(-1, -1, -1);
        } else {
            int x = SloppyDates.uniquePrefixIdx(token, monthNames);
            if (x >= 0 && mm == -1)
                mm = x;
            else
                return new Triple<Integer, Integer, Integer>(-1, -1, -1);
        }
    }
    return new Triple<Integer, Integer, Integer>(dd, mm, yy);
}

From source file:net.sf.webphotos.util.Util.java

/**
 * Ajusta a largura das colunas do modelo.
 *
 * @param tabela Tabela que deseja ajustar as colunas.
 * @param parametros Tamanhos das colunas separadas por vrgula.
 *///  w  w w  .  j a va 2s. c o  m
public static void ajustaLargura(JTable tabela, String parametros) {
    int temR = -1;
    TableColumnModel modeloColunas = tabela.getColumnModel();
    if (parametros == null) {
        return;
    }
    if (parametros.length() > 0) {
        StringTokenizer tok = new StringTokenizer(parametros, ",");
        int ct = 0;
        String l;
        while (tok.hasMoreTokens()) {
            l = tok.nextToken();
            try {
                modeloColunas.getColumn(ct).setPreferredWidth(Integer.parseInt(l));
            } catch (NumberFormatException nE) {
                switch (l) {
                case "*":
                    log.info("Packing column " + ct);
                    packColumn(tabela, ct, 1);
                    break;
                case "R":
                    temR = ct;
                    break;
                }
            } catch (Exception e) {
            }
            ct++;
        }

        if (temR > 0) {
            modeloColunas.getColumn(temR).setPreferredWidth(modeloColunas.getColumn(temR).getPreferredWidth()
                    + tabela.getWidth() - modeloColunas.getTotalColumnWidth());
            log.debug("Tamanho da tabela: " + (modeloColunas.getColumn(temR).getPreferredWidth()
                    + tabela.getWidth() - modeloColunas.getTotalColumnWidth()));
        }

        //Testes
        log.debug("Tamanho Total: " + modeloColunas.getTotalColumnWidth());
        log.debug("Tamanho da tabela: " + tabela.getWidth());
    }
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

public static String[] getCNs(final X509Certificate cert) {
    final LinkedList<String> cnList = new LinkedList<String>();
    /*//from  www .  j  a  v  a2  s  . c  om
      Sebastian Hauer's original StrictSSLProtocolSocketFactory used
      getName() and had the following comment:
            
        Parses a X.500 distinguished name for the value of the
        "Common Name" field.  This is done a bit sloppy right
         now and should probably be done a bit more according to
        <code>RFC 2253</code>.
            
       I've noticed that toString() seems to do a better job than
       getName() on these X500Principal objects, so I'm hoping that
       addresses Sebastian's concern.
            
       For example, getName() gives me this:
       1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
            
       whereas toString() gives me this:
       EMAILADDRESS=juliusdavies@cucbc.com
            
       Looks like toString() even works with non-ascii domain names!
       I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
    */

    final String subjectPrincipal = cert.getSubjectX500Principal().toString();
    final StringTokenizer st = new StringTokenizer(subjectPrincipal, ",+");
    while (st.hasMoreTokens()) {
        final String tok = st.nextToken().trim();
        if (tok.length() > 3) {
            if (tok.substring(0, 3).equalsIgnoreCase("CN=")) {
                cnList.add(tok.substring(3));
            }
        }
    }
    if (!cnList.isEmpty()) {
        final String[] cns = new String[cnList.size()];
        cnList.toArray(cns);
        return cns;
    } else {
        return null;
    }
}

From source file:com.aimluck.eip.util.ALCellularUtils.java

/**
 * ?? ID ????//  w  ww .j  a  v  a 2  s .  c  o m
 * 
 * @param rundata
 * @return
 */
public static String getCellularUid(RunData rundata) {
    String password = "";
    JetspeedRunData data = (JetspeedRunData) rundata;
    String useragent = data.getRequest().getHeader("User-Agent");
    if (useragent != null && useragent.length() > 0) {
        useragent = useragent.trim();
        CapabilityMap cm = CapabilityMapFactory.getCapabilityMap(useragent);
        MimeType mime = cm.getPreferredType();
        if (mime != null) {
            MediaTypeEntry media = (MediaTypeEntry) Registry.getEntry(Registry.MEDIA_TYPE,
                    cm.getPreferredMediaType());
            if ("docomo_imode".equals(media.getName())) {
                int lastindex = useragent.lastIndexOf("ser");
                if (lastindex >= 0) {
                    password = useragent.substring(lastindex, useragent.length());
                }
            } else if ("docomo_foma".equals(media.getName())) {
                StringTokenizer st = new StringTokenizer(useragent, ";");
                String token = null;
                while (st.hasMoreTokens()) {
                    if ((token = st.nextToken()).startsWith("ser")) {
                        password = token.trim();
                        break;
                    }
                }
            } else if ("au".equals(media.getName())) {
                String header = data.getRequest().getHeader("x-up-subno");
                if (header != null && header.length() > 0) {
                    int index = header.indexOf("_");
                    if (index >= 0) {
                        password = header.substring(0, index);
                    }
                }
            } else if ("vodafone".equals(media.getName())) {
                int index = useragent.indexOf("SN");
                if (index >= 0) {
                    int delta = -1;
                    if (useragent.startsWith("J-PHONE/4")) {
                        delta = 10;
                    } else if (useragent.startsWith("J-PHONE/5")) {
                        delta = 15;
                    } else if (useragent.startsWith("Vodafone")) {
                        delta = 15;
                    } else if (useragent.startsWith("SoftBank")) {
                        delta = 15;
                    }
                    if (index >= 0 && delta > 0) {
                        password = useragent.substring(index, index + 2 + delta);
                    }
                } else {
                    String jphoneUid = data.getRequest().getHeader("x-jphone-uid");
                    if (jphoneUid != null) {
                        password = jphoneUid;
                    }
                }
            }
        }
    }
    return password;
}

From source file:azkaban.utils.FileIOUtils.java

public static String getSourcePathFromClass(Class<?> containedClass) {
    File file = new File(containedClass.getProtectionDomain().getCodeSource().getLocation().getPath());

    if (!file.isDirectory() && file.getName().endsWith(".class")) {
        String name = containedClass.getName();
        StringTokenizer tokenizer = new StringTokenizer(name, ".");
        while (tokenizer.hasMoreTokens()) {
            tokenizer.nextElement();//w w w .  ja v  a  2s .c  om
            file = file.getParentFile();
        }
        return file.getPath();
    } else {
        return containedClass.getProtectionDomain().getCodeSource().getLocation().getPath();
    }
}

From source file:com.amalto.core.save.context.PartialUpdateActionCreator.java

private static void resetPath(String currentPath, Stack<String> path) {
    StringTokenizer pathIterator = new StringTokenizer(currentPath, "/"); //$NON-NLS-1$
    path.clear();/*from w  ww.java  2 s  .  c  o  m*/
    while (pathIterator.hasMoreTokens()) {
        path.add(pathIterator.nextToken());
    }
}

From source file:com.sslexplorer.input.tags.VariablesTag.java

/**
 * Method to generate the Replacement Variable Chooser Fragment.
 * //from w  ww  .  ja v  a2  s  . c  o m
 * @param titleKey
 * @param pageContext
 * @param bundle
 * @param locale
 * @param inputId
 * @param variables
 * @param includeSession
 * @param includeUserAttributes
 * @param includeRequest
 * @return String
 * @throws JspException
 */
public static String generateReplacementVariableChooserFragment(String titleKey, PageContext pageContext,
        String bundle, String locale, String inputId, String variables, boolean includeSession,
        boolean includeUserAttributes, boolean includeRequest) throws JspException {
    StringBuffer buf = new StringBuffer();

    String title = null;
    if (titleKey != null) {
        title = TagUtils.getInstance().message(pageContext, bundle, locale, titleKey, new String[] {});
    }
    if (title == null) {
        title = TagUtils.getInstance().message(pageContext, bundle, locale, "replacementVariablesChooser.title",
                new String[] {});
        if (title == null) {
            title = "Replacement Variables";
        }
    }
    buf.append("<div class=\"component_replacementVariablesToggle\">");

    // buf.append("<input type=\"button\"
    // onclick=\"toggleAndPositionBelow(document.getElementById('replacementVariablesChooser");
    // buf.append(inputId);
    // buf.append("'), document.getElementById('");
    // buf.append(inputId);
    // buf.append("'))\" ");
    // buf.append("value=\"${}\"/>");

    buf.append("<img onclick=\"togglePopupBelowLeft(document.getElementById('replacementVariablesChooser");
    buf.append(inputId);
    buf.append("'), document.getElementById('");
    buf.append(inputId);
    buf.append("'))\" ");
    buf.append("src=\"");
    buf.append(CoreUtil.getThemePath(pageContext.getSession()));
    buf.append("/images/variables.gif\"/>");

    buf.append("</div>");
    buf.append("<div id=\"replacementVariablesChooser");
    buf.append(inputId);
    buf.append("\" style=\"position:absolute;display: none;overflow:visible;top:4px;left:4px;z-index:900;\">");
    buf.append("<div class=\"replacementVariablesMain\">");
    buf.append("<div class=\"replacementVariablesTitleBar\">");
    buf.append("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
    buf.append("<tr><td class=\"title\">");
    buf.append(title);
    buf.append("</td><td class=\"close\"><img src=\"");
    buf.append(CoreUtil.getThemePath(pageContext.getSession()));
    buf.append("/images/actions/erase.gif\" ");
    buf.append("onclick=\"document.getElementById('");
    buf.append(inputId);
    buf.append("').value = ''\"/><img src=\"");
    buf.append(CoreUtil.getThemePath(pageContext.getSession()));
    buf.append("/images/actions/closeReplacementVariables.gif\" ");
    buf.append("onclick=\"togglePopup(document.getElementById('replacementVariablesChooser");
    buf.append(inputId);
    buf.append("'))\"/>");
    buf.append("</td></tr></table></div><div class=\"replacementVariablesContent\">");
    buf.append("<ul>");
    if (variables != null) {
        StringTokenizer t = new StringTokenizer(variables, ",");
        while (t.hasMoreTokens()) {
            String n = t.nextToken();
            addVariable(n, n, buf, pageContext, bundle, locale, inputId);
        }
    }
    if (includeSession) {
        addVariable("session:username", null, buf, pageContext, bundle, locale, inputId);
        addVariable("session:password", null, buf, pageContext, bundle, locale, inputId);
        addVariable("session:email", null, buf, pageContext, bundle, locale, inputId);
        addVariable("session:fullname", null, buf, pageContext, bundle, locale, inputId);
        addVariable("session:clientProxyURL", null, buf, pageContext, bundle, locale, inputId);
    }

    if (includeRequest) {
        addVariable("request:serverName", null, buf, pageContext, bundle, locale, inputId);
        addVariable("request:serverPort", null, buf, pageContext, bundle, locale, inputId);
        addVariable("request:userAgent", null, buf, pageContext, bundle, locale, inputId);
    }

    if (includeUserAttributes) {
        Collection<PropertyDefinition> l;
        try {
            for (PropertyClass propertyClass : PropertyClassManager.getInstance().getPropertyClasses()) {
                if (propertyClass instanceof AttributesPropertyClass
                        && !propertyClass.getName().equals(ResourceAttributes.NAME)) {
                    l = propertyClass.getDefinitions();
                    for (PropertyDefinition d : l) {
                        AttributeDefinition def = (AttributeDefinition) d;
                        if (def.isReplaceable()) {
                            addVariable(def.getPropertyClass().getName() + ":" + def.getName(),
                                    def.getDescription(), buf, pageContext, bundle, locale, inputId);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Failed to get user attribute definitions.");
        }
    }
    buf.append("</ul>");
    buf.append("</div>");
    buf.append("</div>");
    return buf.toString();
}