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:azkaban.jobtype.HadoopSparkJob.java

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

    if (!file.isDirectory() && file.getName().endsWith(".class")) {
        final String name = containedClass.getName();
        final StringTokenizer tokenizer = new StringTokenizer(name, ".");
        while (tokenizer.hasMoreTokens()) {
            tokenizer.nextElement();/*from  w w  w .  jav  a2 s.  c  om*/
            file = file.getParentFile();
        }

        return file.getPath();
    } else {
        return containedClass.getProtectionDomain().getCodeSource().getLocation().getPath();
    }
}

From source file:com.adito.agent.client.ProxyUtil.java

/**
 * Attempt to proxy settings from Firefox.
 * // www .  j a  v a2  s . com
 * @return firefox proxy settings
 * @throws IOException if firefox settings could not be obtained for some
 *         reason
 */
public static BrowserProxySettings lookupFirefoxProxySettings() throws IOException {

    try {

        Vector proxies = new Vector();
        Vector bypassAddr = new Vector();

        File home = new File(Utils.getHomeDirectory());
        File firefoxAppData;

        if (System.getProperty("os.name") != null && System.getProperty("os.name").startsWith("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            firefoxAppData = new File(home, "Application Data\\Mozilla\\Firefox\\profiles.ini"); //$NON-NLS-1$
        } else {
            firefoxAppData = new File(home, ".mozilla/firefox/profiles.ini"); //$NON-NLS-1$
        }

        // Look for Path elements in the profiles.ini
        BufferedReader reader = null;
        Hashtable profiles = new Hashtable();
        String line;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(firefoxAppData)));
            String currentProfileName = ""; //$NON-NLS-1$

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("[") && line.endsWith("]")) { //$NON-NLS-1$ //$NON-NLS-2$
                    currentProfileName = line.substring(1, line.length() - 1);
                    continue;
                }

                if (line.startsWith("Path=")) { //$NON-NLS-1$
                    profiles.put(currentProfileName, new File(firefoxAppData.getParent(), line.substring(5)));
                }
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        // Iterate through all the profiles and load the proxy infos from
        // the prefs.js file

        File prefsJS;
        String profileName;
        for (Enumeration e = profiles.keys(); e.hasMoreElements();) {
            profileName = (String) e.nextElement();
            prefsJS = new File((File) profiles.get(profileName), "prefs.js"); //$NON-NLS-1$
            Properties props = new Properties();
            reader = null;
            try {
                if (!prefsJS.exists()) {
                    // needed to defend against un-initialised profiles.
                    // #ifdef DEBUG
                    log.info("The file " + prefsJS.getAbsolutePath() + " does not exist."); //$NON-NLS-1$
                    // #endif
                    // now remove it from the map.
                    profiles.remove(profileName);
                    continue;
                }
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(prefsJS)));
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("user_pref(\"")) { //$NON-NLS-1$
                        int idx = line.indexOf("\"", 11); //$NON-NLS-1$
                        if (idx == -1)
                            continue;
                        String pref = line.substring(11, idx);

                        // Save this position
                        int pos = idx + 1;

                        // Look for another quote
                        idx = line.indexOf("\"", idx + 1); //$NON-NLS-1$

                        String value;
                        if (idx == -1) {
                            // No more quotes
                            idx = line.indexOf(" ", pos); //$NON-NLS-1$

                            if (idx == -1)
                                continue;

                            int idx2 = line.indexOf(")", pos); //$NON-NLS-1$

                            if (idx2 == -1)
                                continue;

                            value = line.substring(idx + 1, idx2);

                        } else {

                            // String value
                            int idx2 = line.indexOf("\"", idx + 1); //$NON-NLS-1$

                            if (idx2 == -1)
                                continue;

                            value = line.substring(idx + 1, idx2);
                        }

                        props.put(pref, value);

                    }
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            ProxyInfo p;
            /**
             * Extract some proxies from the properites, if the proxy is
             * enabled
             */
            if ("1".equals(props.get("network.proxy.type"))) { //$NON-NLS-1$ //$NON-NLS-2$
                boolean isProfileActive = checkProfileActive(prefsJS);
                if (props.containsKey("network.proxy.ftp")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "ftp=" + props.get("network.proxy.ftp") + ":" + props.get("network.proxy.ftp_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.http")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "http=" + props.get("network.proxy.http") + ":" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                    + props.get("network.proxy.http_port"), //$NON-NLS-1$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.ssl")) { //$NON-NLS-1$
                    p = createProxyInfo(
                            "ssl=" + props.get("network.proxy.ssl") + ":" + props.get("network.proxy.ssl_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                            "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.socks")) { //$NON-NLS-1$
                    p = createProxyInfo("socks=" + props.get("network.proxy.socks") + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            + props.get("network.proxy.socks_port"), "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    p.setActiveProfile(isProfileActive);
                    proxies.addElement(p);
                }

                if (props.containsKey("network.proxy.no_proxies_on")) { //$NON-NLS-1$

                    StringTokenizer tokens = new StringTokenizer(
                            props.getProperty("network.proxy.no_proxies_on"), ","); //$NON-NLS-1$ //$NON-NLS-2$

                    while (tokens.hasMoreTokens()) {
                        bypassAddr.addElement(((String) tokens.nextToken()).trim());
                    }

                }
            }
        }

        // need to ensure that the returned values are sorted correctly...
        BrowserProxySettings bps = new BrowserProxySettings();
        bps.setBrowser("Mozilla Firefox"); //$NON-NLS-1$
        bps.setProxiesActiveFirst(proxies);
        bps.setBypassAddr(new String[bypassAddr.size()]);
        bypassAddr.copyInto(bps.getBypassAddr());
        return bps;

    } catch (Throwable t) {
        throw new IOException("Failed to get proxy information from Firefox profiles: " + t.getMessage()); //$NON-NLS-1$
    }
}

From source file:ClassFinder.java

private static List getClasspathMatches(String[] strPathsOrJars) {

    StringTokenizer classPaths = new StringTokenizer(System.getProperty("java.class.path"), // $NON-NLS-1$
            System.getProperty("path.separator")); // $NON-NLS-1$

    // find all jar files or paths that end with strPathOrJar
    ArrayList<String> listPaths = new ArrayList<String>();
    String classPath = null;//from  www. j  av a 2s. com
    while (classPaths.hasMoreTokens()) {
        classPath = fixPathEntry(classPaths.nextToken());
        if (strPathsOrJars == null) {
            listPaths.add(classPath);
        } else {
            boolean found = false;
            for (String strPathsOrJar : strPathsOrJars) {
                if (classPath.endsWith(strPathsOrJar)) {
                    found = true;
                    listPaths.add(classPath);
                    break;// no need to look further
                }
            }
            if (!found) {
                // log.debug("Did not find: " + strPath);
            }
        }
    }
    return listPaths;
}

From source file:net.objectlab.kit.util.StringUtil.java

/**
 * Takes a block of text which might have long lines in it and wraps
 * the long lines based on the supplied wrapColumn parameter. It was
 * initially implemented for use by VelocityEmail. If there are tabs
 * in inString, you are going to get results that are a bit strange,
 * since tabs are a single character but are displayed as 4 or 8
 * spaces. Remove the tabs.//from   w  w w  .ja v a 2s .c  o m
 *
 * @param inString   Text which is in need of word-wrapping.
 * @param newline    The characters that define a newline.
 * @param wrapColumn The column to wrap the words at.
 * @return           The text with all the long lines word-wrapped.
 */
public static String wrapText(final String inString, final String newline, final int wrapColumn) {
    if (inString == null) {
        return null;
    }
    final StringTokenizer lineTokenizer = new StringTokenizer(inString, newline, true);
    final StringBuilder builder = new StringBuilder();

    while (lineTokenizer.hasMoreTokens()) {
        try {
            String nextLine = lineTokenizer.nextToken();

            if (nextLine.length() > wrapColumn) {
                // This line is long enough to be wrapped.
                nextLine = wrapLine(nextLine, newline, wrapColumn);
            }

            builder.append(nextLine);
        } catch (final NoSuchElementException nsee) {
            // thrown by nextToken(), but I don't know why it would
            break;
        }
    }

    return builder.toString();
}

From source file:edu.psu.citeseerx.updates.IndexUpdateManager.java

/**
 * Builds a list of author normalizations to create more flexible
 * author search./*from   ww w . j  a va2s  .  c  om*/
 * @param names
 * @return
 */
private static List<String> buildAuthorNorms(List<String> names) {
    HashSet<String> norms = new HashSet<String>();
    for (String name : names) {
        name = name.replaceAll("[^\\p{L} ]", "");
        StringTokenizer st = new StringTokenizer(name);
        String[] tokens = new String[st.countTokens()];
        int counter = 0;
        while (st.hasMoreTokens()) {
            tokens[counter] = st.nextToken();
            counter++;
        }
        norms.add(joinStringArray(tokens));

        if (tokens.length > 2) {

            String[] n1 = new String[tokens.length];
            for (int i = 0; i < tokens.length; i++) {
                if (i < tokens.length - 1) {
                    n1[i] = Character.toString(tokens[i].charAt(0));
                } else {
                    n1[i] = tokens[i];
                }
            }

            String[] n2 = new String[tokens.length];
            for (int i = 0; i < tokens.length; i++) {
                if (i > 0 && i < tokens.length - 1) {
                    n2[i] = Character.toString(tokens[i].charAt(0));
                } else {
                    n2[i] = tokens[i];
                }
            }

            norms.add(joinStringArray(n1));
            norms.add(joinStringArray(n2));
        }

        if (tokens.length > 1) {

            String[] n3 = new String[2];
            n3[0] = tokens[0];
            n3[1] = tokens[tokens.length - 1];

            String[] n4 = new String[2];
            n4[0] = Character.toString(tokens[0].charAt(0));
            n4[1] = tokens[tokens.length - 1];

            norms.add(joinStringArray(n3));
            norms.add(joinStringArray(n4));
        }
    }

    ArrayList<String> normList = new ArrayList<String>();
    for (Iterator<String> it = norms.iterator(); it.hasNext();) {
        normList.add(it.next());
    }

    return normList;
}

From source file:StringUtil.java

/**
 * Splits the provided text into a list, based on a given separator.
 * The separator is not included in the returned String array.
 * The maximum number of splits to perfom can be controlled.
 * A null separator will cause parsing to be on whitespace.
 *
 * <p>This is useful for quickly splitting a string directly into
 * an array of tokens, instead of an enumeration of tokens (as
 * <code>StringTokenizer</code> does).
 *
 * @param str The string to parse.//w w w. j  a  v a2s.c o m
 * @param separator Characters used as the delimiters. If
 * <code>null</code>, splits on whitespace.
 * @param max The maximum number of elements to include in the
 * list.  A zero or negative value implies no limit.
 * @return an array of parsed Strings 
 */
public static String[] split(String str, String separator, int max) {
    StringTokenizer tok = null;
    if (separator == null) {
        // Null separator means we're using StringTokenizer's default
        // delimiter, which comprises all whitespace characters.
        tok = new StringTokenizer(str);
    } else {
        tok = new StringTokenizer(str, separator);
    }

    int listSize = tok.countTokens();
    if (max > 0 && listSize > max) {
        listSize = max;
    }

    String[] list = new String[listSize];
    int i = 0;
    int lastTokenBegin = 0;
    int lastTokenEnd = 0;
    while (tok.hasMoreTokens()) {
        if (max > 0 && i == listSize - 1) {
            // In the situation where we hit the max yet have
            // tokens left over in our input, the last list
            // element gets all remaining text.
            String endToken = tok.nextToken();
            lastTokenBegin = str.indexOf(endToken, lastTokenEnd);
            list[i] = str.substring(lastTokenBegin);
            break;
        } else {
            list[i] = tok.nextToken();
            lastTokenBegin = str.indexOf(list[i], lastTokenEnd);
            lastTokenEnd = lastTokenBegin + list[i].length();
        }
        i++;
    }
    return list;
}

From source file:com.bizosys.dataservice.util.StringUtils.java

/**
 * returns an arraylist of strings  //from   w w w . jav  a  2 s  . c o m
 * @param str the comma seperated string values
 * @return the arraylist of the comma seperated string values
 */
public static Set<String> getUniqueStrings(String str) {
    if (str == null)
        return EMPTY_SET;

    StringTokenizer tokenizer = new StringTokenizer(str, ",");
    Set<String> values = new HashSet<String>();
    while (tokenizer.hasMoreTokens()) {
        values.add(tokenizer.nextToken());
    }
    return values;
}

From source file:com.frameworkset.commons.dbcp2.BasicDataSourceFactory.java

/**
 * Parse list of property values from a delimited string
 * @param value delimited list of values
 * @param delimiter character used to separate values in the list
 * @return String Collection of values/*from   w w  w.java2s .  co  m*/
 */
private static Collection<String> parseList(String value, char delimiter) {
    StringTokenizer tokenizer = new StringTokenizer(value, Character.toString(delimiter));
    Collection<String> tokens = new ArrayList<String>(tokenizer.countTokens());
    while (tokenizer.hasMoreTokens()) {
        tokens.add(tokenizer.nextToken());
    }
    return tokens;
}

From source file:com.cloud.api.ApiDispatcher.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation)
        throws IllegalArgumentException, ParseException {
    try {/* w w  w. java 2s.  c o m*/
        field.setAccessible(true);
        CommandType fieldType = annotation.type();
        switch (fieldType) {
        case BOOLEAN:
            field.set(cmdObj, Boolean.valueOf(paramObj.toString()));
            break;
        case DATE:
            // This piece of code is for maintaining backward compatibility
            // and support both the date formats(Bug 9724)
            // Do the date messaging for ListEventsCmd only
            if (cmdObj instanceof ListEventsCmd) {
                boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString());
                if (isObjInNewDateFormat) {
                    DateFormat newFormat = BaseCmd.NEW_INPUT_FORMAT;
                    synchronized (newFormat) {
                        field.set(cmdObj, newFormat.parse(paramObj.toString()));
                    }
                } else {
                    DateFormat format = BaseCmd.INPUT_FORMAT;
                    synchronized (format) {
                        Date date = format.parse(paramObj.toString());
                        if (field.getName().equals("startDate")) {
                            date = messageDate(date, 0, 0, 0);
                        } else if (field.getName().equals("endDate")) {
                            date = messageDate(date, 23, 59, 59);
                        }
                        field.set(cmdObj, date);
                    }
                }
            } else {
                DateFormat format = BaseCmd.INPUT_FORMAT;
                format.setLenient(false);
                synchronized (format) {
                    field.set(cmdObj, format.parse(paramObj.toString()));
                }
            }
            break;
        case FLOAT:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Float.valueOf(paramObj.toString()));
            }
            break;
        case INTEGER:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Integer.valueOf(paramObj.toString()));
            }
            break;
        case LIST:
            List listParam = new ArrayList();
            StringTokenizer st = new StringTokenizer(paramObj.toString(), ",");
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                CommandType listType = annotation.collectionType();
                switch (listType) {
                case INTEGER:
                    listParam.add(Integer.valueOf(token));
                    break;
                case UUID:
                    if (token.isEmpty())
                        break;
                    Long internalId = translateUuidToInternalId(token, annotation);
                    listParam.add(internalId);
                    break;
                case LONG: {
                    listParam.add(Long.valueOf(token));
                }
                    break;
                case SHORT:
                    listParam.add(Short.valueOf(token));
                case STRING:
                    listParam.add(token);
                    break;
                }
            }
            field.set(cmdObj, listParam);
            break;
        case UUID:
            if (paramObj.toString().isEmpty())
                break;
            Long internalId = translateUuidToInternalId(paramObj.toString(), annotation);
            field.set(cmdObj, internalId);
            break;
        case LONG:
            field.set(cmdObj, Long.valueOf(paramObj.toString()));
            break;
        case SHORT:
            field.set(cmdObj, Short.valueOf(paramObj.toString()));
            break;
        case STRING:
            if ((paramObj != null) && paramObj.toString().length() > annotation.length()) {
                s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: "
                        + field.getName());
                throw new InvalidParameterValueException("Value greater than max allowed length "
                        + annotation.length() + " for param: " + field.getName());
            }
            field.set(cmdObj, paramObj.toString());
            break;
        case TZDATE:
            field.set(cmdObj, DateUtil.parseTZDateString(paramObj.toString()));
            break;
        case MAP:
        default:
            field.set(cmdObj, paramObj);
            break;
        }
    } catch (IllegalAccessException ex) {
        s_logger.error("Error initializing command " + cmdObj.getCommandName() + ", field " + field.getName()
                + " is not accessible.");
        throw new CloudRuntimeException("Internal error initializing parameters for command "
                + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]");
    }
}

From source file:ScribbleDragAndDrop.java

/**
 * Create a new Scribble object and initialize it by parsing a string of
 * coordinate data in the format produced by toString()
 *//*  w  w  w.java2s .c  o  m*/
public static Scribble parse(String s) throws NumberFormatException {
    StringTokenizer st = new StringTokenizer(s);
    Scribble scribble = new Scribble();
    while (st.hasMoreTokens()) {
        String t = st.nextToken();
        if (t.charAt(0) == 'm') {
            scribble.moveto(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
        } else {
            scribble.lineto(Double.parseDouble(t), Double.parseDouble(st.nextToken()));
        }
    }
    return scribble;
}