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.ucla.stat.SOCR.chart.ChartTree_dynamic.java

private void createTreeModel(BufferedReader rder) {
    //System.out.println("CreateTreeModel:start");      

    String[] nodeList;/*w w  w.  j  a  va 2  s. c  o  m*/
    String line;
    if (treeRootName == null)
        root = new DefaultMutableTreeNode("SOCRCharts");
    else
        root = new DefaultMutableTreeNode(treeRootName);

    StringBuffer sb = new StringBuffer();

    while ((line = readLine(rder)) != null && !(line.toLowerCase().startsWith("["))) {
        if (line.toLowerCase().startsWith("subcategory")) {
            line = line.substring(line.indexOf("=") + 1);
            sb.append(line.trim());
            sb.append(",");
        } //ignore other cases 
    }

    StringTokenizer tk = new StringTokenizer(new String(sb), ",");
    nodeList = new String[tk.countTokens()];
    int i = 0;
    while (tk.hasMoreTokens()) {
        nodeList[i] = tk.nextToken();
        i++;
    }

    for (i = 0; i < nodeList.length; i++) {
        //System.out.println(nodeList[i]);
        root.add(createChartsNode(nodeList[i]));
    }
}

From source file:net.sf.excelutils.tags.CallTag.java

public int[] parseTag(Object context, Workbook wb, Sheet sheet, Row curRow, Cell curCell)
        throws ExcelException {

    String cellstr = curCell.getStringCellValue();

    LOG.debug("CallTag:" + cellstr);

    if (null == cellstr || "".equals(cellstr)) {
        return new int[] { 0, 0, 0 };
    }/*from   w ww .j av  a2s. co  m*/

    cellstr = cellstr.substring(KEY_CALL.length()).trim();
    String serviceName = cellstr.substring(0, cellstr.indexOf('.'));
    String methodName = cellstr.substring(cellstr.indexOf('.') + 1, cellstr.indexOf('('));
    String paramStr = cellstr.substring(cellstr.indexOf('(') + 1, cellstr.lastIndexOf(')'));
    String propertyName = cellstr.substring(cellstr.lastIndexOf(')') + 1);

    Object[] params = new Object[0];
    Class[] types = new Class[0];
    // prepare params
    if (!"".equals(paramStr) && null != paramStr) {
        StringTokenizer st = new StringTokenizer(paramStr, ",");
        params = new Object[st.countTokens()];
        types = new Class[st.countTokens()];
        int index = 0;
        while (st.hasMoreTokens()) {
            String param = st.nextToken().trim();
            // get param type & value
            types[index] = getParamType(param);
            if ("java.lang.Object".equals(types[index].getName())) {
                params[index] = ExcelParser.parseStr(context, param);
                types[index] = params[index].getClass();
            } else if ("boolean".equals(types[index].getName())) {
                params[index] = Boolean.valueOf(param);
            } else if ("int".equals(types[index].getName())) {
                params[index] = Integer.valueOf(param);
            } else if ("double".equals(types[index].getName())) {
                params[index] = Double.valueOf(param);
            } else if ("java.lang.String".equals(types[index].getName())) {
                params[index] = param.substring(1, param.length() - 1);
            }
            index++;
        }
    }

    // get the service
    Object service = ExcelParser.getValue(context, serviceName);
    if (null == service) {
        return new int[] { 0, 0, 0 };
    }

    // get the method
    Method method = findMethod(service, methodName, types);
    if (null == method) {
        return new int[] { 0, 0, 0 };
    }

    // invoke method
    try {
        Object result = method.invoke(service, params);
        // put the result to context
        ExcelUtils.addValue(context, serviceName + methodName, result);
        // curCell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
        curCell.setCellValue("${" + serviceName + methodName + propertyName + "}");
        ExcelParser.parseCell(context, sheet, curRow, curCell);
    } catch (Exception e) {

    }

    return new int[] { 0, 0, 0 };
}

From source file:op.tools.SYSCalendar.java

/**
 * Expiry dates usually have a form like "12-10" oder "12/10" to indicate that the product in question is
 * best before December 31st, 2010. This method parses dates like this.
 * If it fails it hands over the parsing efforts to <code>public static Date parseDate(String input)</code>.
 *
 * @param input a string to be parsed. It can handle the following formats "mm/yy", "mm/yyyy" (it also recognizes these kinds of
 *              dates if the slash is replaced with one of the following chars: "-,.".
 * @return the parsed date which is always the last day and the last second of that month.
 * @throws NumberFormatException/*  www.j a  v  a2s. com*/
 */
public static DateTime parseExpiryDate(String input) throws NumberFormatException {
    if (input == null || input.isEmpty()) {
        throw new NumberFormatException("empty");
    }
    input = input.trim();
    if (input.indexOf(".") + input.indexOf(",") + input.indexOf("-") + input.indexOf("/") == -4) {
        input += ".";
    }

    StringTokenizer st = new StringTokenizer(input, "/,.-");
    if (st.countTokens() == 1) { // only one number, then this must be the month. we add the current year.
        input = "1." + input + SYSCalendar.today().get(GregorianCalendar.YEAR);
    }
    if (st.countTokens() == 2) { // complete expiry date. we fill up some dummy day.
        input = "1." + input;
        //st = new StringTokenizer(input, "/,.-"); // split again...
    }
    DateTime expiry = new DateTime(parseDate(input));

    // when the user has entered a complete date, then we return that date
    // if he has omitted some parts of it, we consider it always the last day of that month.
    return st.countTokens() == 3 ? expiry
            : expiry.dayOfMonth().withMaximumValue().secondOfDay().withMaximumValue();

}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server//from ww  w.j a va 2  s . com
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

        // set the Date: header
        msg.setSentDate(new Date());

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}

From source file:it.unibas.spicy.persistence.xml.operators.UpdateDataSourceWithConstraints.java

private List<String> normalizePath(String path) {
    String currentPath = path;//from   www.j a v  a  2  s .  c om
    ArrayList<String> list = new ArrayList<String>();
    if (currentPath.startsWith(".")) {
        currentPath = path.substring(1);
    }
    currentPath = currentPath.replaceAll("\\@", "");
    currentPath = currentPath.replaceAll("\\*", "");

    StringTokenizer tokenizer = new StringTokenizer(currentPath, "/");
    if (tokenizer.countTokens() > 0) {
        if (logger.isDebugEnabled())
            logger.debug(" --- Tokenizer for " + path + " with " + tokenizer.countTokens() + " elements");
        while (tokenizer.hasMoreElements()) {
            String token = tokenizer.nextToken();
            if (!(token.trim().equals(""))) {
                if (logger.isDebugEnabled())
                    logger.debug("\t +" + token + " added");
                list.add(token);
            }
        }
    } else {
        if (!(currentPath.trim().equals(""))) {
            if (logger.isDebugEnabled())
                logger.debug("\t +" + currentPath + " added");
            list.add(currentPath);
        }

    }

    if (logger.isDebugEnabled())
        logger.debug(" --- Size of list for " + path + " is = " + list.size());
    return list;
}

From source file:com.google.android.exoplayer.upstream.FtpDataSource.java

@Override
public long open(DataSpec dataSpec) throws FtpDataSourceException {
    this.dataSpec = dataSpec;
    String host = dataSpec.uri.getHost();
    int port = dataSpec.uri.getPort();
    if (port <= 0)
        port = FTP.DEFAULT_PORT;//from w  w  w  .  j av  a 2 s .  c  o  m
    String filePath = dataSpec.uri.getPath();
    String userInfo = dataSpec.uri.getUserInfo();
    Log.i("ftp", "fpt login:" + dataSpec.uri.toString() + " " + dataSpec.position);
    String user = "anonymous", pass = "";

    if (userInfo != null) {
        StringTokenizer tok = new StringTokenizer(userInfo, ":@");
        if (tok.countTokens() > 0) {
            user = tok.nextToken();
            if (tok.hasMoreTokens())
                pass = tok.nextToken();
        }
    }

    try {
        long start_time = System.currentTimeMillis();
        ftpClient.connect(host, port);
        isConnect = FTPReply.isPositiveCompletion(ftpClient.getReplyCode());
        if (!isConnect)
            throw new FtpDataSourceException("connect failed.");
        Log.i("ftp", "ftp connect use:" + (System.currentTimeMillis() - start_time));

        isLogin = ftpClient.login(user, pass);
        Log.i("ftp", "ftp login use:" + (System.currentTimeMillis() - start_time));
        Log.i("ftp", "fpt login:" + user + ":" + pass + "@" + host + ":" + port + " - " + isLogin);
        if (!isLogin)
            throw new FtpDataSourceException("login failed.");

        fileSize = getFileSize(ftpClient, filePath);

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);
        ftpClient.setRestartOffset(dataSpec.position);
        stream = ftpClient.retrieveFileStream(filePath);
        bytesRemaining = dataSpec.length == C.LENGTH_UNBOUNDED ? fileSize - dataSpec.position : dataSpec.length;
    } catch (IOException e) {
        throw new FtpDataSourceException(e);
    }

    opened = true;
    if (listener != null) {
        listener.onTransferStart();
    }
    return bytesRemaining;
}

From source file:com.l2jfree.gameserver.model.MacroList.java

public void restore() {
    _macroses.clear();/*from  www  .j  ava 2  s.com*/
    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(
                "SELECT id, icon, name, descr, acronym, commands FROM character_macroses WHERE charId=?");
        statement.setInt(1, _owner.getObjectId());
        ResultSet rset = statement.executeQuery();
        while (rset.next()) {
            int id = rset.getInt("id");
            int icon = rset.getInt("icon");
            String name = rset.getString("name");
            String descr = rset.getString("descr");
            String acronym = rset.getString("acronym");
            List<L2MacroCmd> commands = new FastList<L2MacroCmd>();
            StringTokenizer st1 = new StringTokenizer(rset.getString("commands"), ";");
            while (st1.hasMoreTokens()) {
                StringTokenizer st = new StringTokenizer(st1.nextToken(), ",");
                if (st.countTokens() < 3)
                    continue;
                int type = Integer.parseInt(st.nextToken());
                int d1 = Integer.parseInt(st.nextToken());
                int d2 = Integer.parseInt(st.nextToken());
                String cmd = "";
                if (st.hasMoreTokens())
                    cmd = st.nextToken();
                L2MacroCmd mcmd = new L2MacroCmd(commands.size(), type, d1, d2, cmd);
                commands.add(mcmd);
            }

            L2Macro m = new L2Macro(id, icon, name, descr, acronym,
                    commands.toArray(new L2MacroCmd[commands.size()]));
            _macroses.put(m.id, m);
        }
        rset.close();
        statement.close();
    } catch (Exception e) {
        _log.warn("could not store shortcuts:", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.blocks.framework.utils.date.StringUtil.java

/**
  * ?,,?????, ??, ?JAVA?????./*from  ww w.  ja v  a  2 s  .  c  o m*/
  * 
  * @param columnName
  *            String ???
  * 
  * @return String ???
  * 
  */
 public static String getStandardStr(String columnName) {
     columnName = columnName.toLowerCase();
     StringBuffer sb = new StringBuffer();
     StringTokenizer token = new StringTokenizer(columnName, "_");
     int itoken = token.countTokens();
     for (int i = 0; i < itoken; i++) {
         if (i == 0) {
             sb.append(token.nextToken());
         } else {
             String temp = token.nextToken();
             sb.append(temp.substring(0, 1).toUpperCase());
             sb.append(temp.substring(1));
         }
     }
     return sb.toString();
 }

From source file:com.ss.language.model.gibblda.Dictionary.java

/**
 * read dictionary from file/*from  www.j  av  a 2s.co m*/
 */
public boolean readWordMap(String wordMapFile) {
    try {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(wordMapFile), "UTF-8"));
        String line;

        // read the number of words
        line = reader.readLine();
        line = LDADataset.removeBomIfNessecery(line);
        int nwords = Integer.parseInt(line);

        // read map
        for (int i = 0; i < nwords; ++i) {
            line = reader.readLine();
            if (line == null || line.trim().isEmpty()) {
                continue;
            }
            StringTokenizer tknr = new StringTokenizer(line, " \t\n\r");

            if (tknr.countTokens() != 2)
                continue;

            String id = tknr.nextToken();
            String word = tknr.nextToken();
            System.out.println(word);
            LuceneDataAccess.save(dicName + id, word);
        }

        reader.close();
        return true;
    } catch (Exception e) {
        System.out.println("Error while reading dictionary:" + e.getMessage());
        e.printStackTrace();
        return false;
    }
}

From source file:de.suse.swamp.core.filter.ContentFilter.java

private ArrayList getChildDatasetNames() {
    ArrayList sets = new ArrayList();
    StringTokenizer st = new StringTokenizer(databitPath, ".");
    st.nextToken();//from  w  w  w .ja  va2s  .com
    while (st.countTokens() > 1) {
        sets.add(st.nextToken());
    }
    return sets;
}