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:org.openvpms.component.business.domain.im.security.ArchetypeAwareGrantedAuthority.java

/**
 * Construct an instance given the string representation of the
 * authority// w  ww  . j  a v a 2 s . c o m
 *
 * @param str a stringified version of the authority
 */
public ArchetypeAwareGrantedAuthority(String str) {
    StringTokenizer tokens = new StringTokenizer(str, ":");
    if (tokens.countTokens() != 3) {
        throw new GrantedAuthorityException(GrantedAuthorityException.ErrorCode.InvalidGrantAuthorityFormat,
                new Object[] { str });
    }

    // the first token must be the prefix
    if (!tokens.nextToken().equals(prefix)) {
        throw new GrantedAuthorityException(GrantedAuthorityException.ErrorCode.InvalidPrefix);
    }

    // the second token is the service and the method. The service 
    // cannot have any wildcards but the method can.
    StringTokenizer temp = new StringTokenizer(tokens.nextToken(), ".");
    if (temp.countTokens() != 2) {
        throw new GrantedAuthorityException(GrantedAuthorityException.ErrorCode.InvalidServiceMethodFormat,
                new Object[] { temp });
    }

    serviceName = temp.nextToken();
    method = temp.nextToken();
    archetypeShortName = tokens.nextToken();

    // store the original str
    this.authority = str;
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static String toDisplay(String url) {
    StringTokenizer tokenizer = new StringTokenizer(url, "/");
    int tokens = tokenizer.countTokens();

    if (tokens > 5) {
        StringBuffer result = new StringBuffer();

        for (int i = 0; i < tokens; i++) {
            if (i == 0) {
                result.append(tokenizer.nextToken());
                result.append("/");
            } else if (i == 1) {
                result.append(tokenizer.nextToken());
                result.append("/...");
            } else if (i >= tokens - 3) {
                result.append("/");
                result.append(tokenizer.nextToken());
            } else {
                tokenizer.nextToken();//from  w  ww  .j  a  v a 2  s. c  o  m
            }
        }

        return result.toString();
    }

    return url;
}

From source file:com.soulgalore.crawler.guice.HttpClientProvider.java

/**
 * Get the client.//from  w  w w.java2 s .c o m
 * 
 * @return the client
 */
public HttpClient get() {
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    cm.setMaxTotal(nrOfThreads);
    cm.setDefaultMaxPerRoute(maxToRoute);
    final DefaultHttpClient client = HTTPSFaker.getClientThatAllowAnyHTTPS(cm);

    client.getParams().setParameter("http.socket.timeout", socketTimeout);
    client.getParams().setParameter("http.connection.timeout", connectionTimeout);

    client.addRequestInterceptor(new RequestAcceptEncoding());
    client.addResponseInterceptor(new ResponseContentEncoding());

    CookieSpecFactory csf = new CookieSpecFactory() {
        public CookieSpec newInstance(HttpParams params) {
            return new BestMatchSpecWithURLErrorLog();
        }
    };

    client.getCookieSpecs().register("bestmatchwithurl", csf);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "bestmatchwithurl");

    if (!"".equals(proxy)) {
        StringTokenizer token = new StringTokenizer(proxy, ":");

        if (token.countTokens() == 3) {
            String proxyProtocol = token.nextToken();
            String proxyHost = token.nextToken();
            int proxyPort = Integer.parseInt(token.nextToken());

            HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol);
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } else
            System.err.println("Invalid proxy configuration: " + proxy);
    }

    if (auths.size() > 0) {

        for (Auth authObject : auths) {
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(authObject.getScope(), authObject.getPort()),
                    new UsernamePasswordCredentials(authObject.getUserName(), authObject.getPassword()));
        }
    }

    return client;
}

From source file:cn.ctyun.amazonaws.services.s3.internal.Mimetypes.java

/**
 * Reads and stores the mime type setting corresponding to a file extension, by reading
 * text from an InputStream. If a mime type setting already exists when this method is run,
 * the mime type value is replaced with the newer one.
 *
 * @param is/*from   w w  w .j a v a2s .co m*/
 *
 * @throws IOException
 */
public void loadAndReplaceMimetypes(InputStream is) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = null;

    while ((line = br.readLine()) != null) {
        line = line.trim();

        if (line.startsWith("#") || line.length() == 0) {
            // Ignore comments and empty lines.
        } else {
            StringTokenizer st = new StringTokenizer(line, " \t");
            if (st.countTokens() > 1) {
                String mimetype = st.nextToken();
                while (st.hasMoreTokens()) {
                    String extension = st.nextToken();
                    extensionToMimetypeMap.put(extension, mimetype);
                    if (log.isDebugEnabled()) {
                        log.debug("Setting mime type for extension '" + extension + "' to '" + mimetype + "'");
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Ignoring mimetype with no associated file extensions: '" + line + "'");
                }
            }
        }
    }
}

From source file:com.alfaariss.oa.util.web.RemoteAddrFilter.java

/**
 * Initializes the <code>RemoteAddrFilter</code>.
 * //from  www .  j  a  v  a2s . c  o  m
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 */
public void init(FilterConfig oFilterConfig) throws ServletException {
    try {
        //Get filter name
        _sFilterName = oFilterConfig.getFilterName();
        if (_sFilterName == null)
            _sFilterName = RemoteAddrFilter.class.getSimpleName();

        //Read allowed IP from parameter
        _sIP = oFilterConfig.getInitParameter("allow");
        if (_sIP == null) {
            _logger.error("No 'allow' init parameter found in filter configuration");
            throw new OAException(SystemErrors.ERROR_INIT);
        }

        _sIP = _sIP.trim();

        StringTokenizer st = new StringTokenizer(_sIP, ",");
        if (st.countTokens() < 1) {
            _logger.error("Invalid 'allow' init parameter found in filter configuration");
            throw new OAException(SystemErrors.ERROR_INIT);
        }
        _logger.info("Only allowing requests from: " + _sIP);

        _logger.info(_sFilterName + " started");
    } catch (OAException e) {
        _logger.fatal(_sFilterName + " start failed", e);
        throw new ServletException();
    } catch (Exception e) {
        _logger.fatal(_sFilterName + " start failed due to internal error", e);
        throw new ServletException();
    }
}

From source file:es.mityc.firmaJava.configuracion.DespliegueConfiguracionMng.java

/**
 * Constructor.//  w  w w .  j  a  v a 2 s. c  om
 * 
 * Recupera los ficheros de configuracin que se utilizarn para el despliegue 
 */
protected DespliegueConfiguracionMng() {
    try {
        ResourceBundle rb = ResourceBundle.getBundle(ConstantesConfiguracion.STR_DESPLIEGUE);
        String files = rb.getString(ConstantesConfiguracion.STR_DESPLIEGUE_CONF_FILE);
        if (files != null) {
            StringTokenizer st = new StringTokenizer(files, ConstantesConfiguracion.COMA);
            props = new ArrayList<ResourceBundle>(st.countTokens());
            boolean hasNext = st.hasMoreTokens();
            while (hasNext) {
                String file = st.nextToken();
                hasNext = st.hasMoreTokens();
                try {
                    props.add(ResourceBundle.getBundle(file));
                } catch (MissingResourceException ex) {
                    log.debug(ST_NO_RECURSOS_FILE + ConstantesConfiguracion.ESPACIO + file);
                }
            }
        }
    } catch (MissingResourceException ex) {
        log.debug(ConstantesConfiguracion.STR_RECURSO_NO_DISPONIBLE, ex);
    }
}

From source file:com.amazonaws.services.s3.internal.Mimetypes.java

/**
 * Reads and stores the mime type setting corresponding to a file extension, by reading
 * text from an InputStream. If a mime type setting already exists when this method is run,
 * the mime type value is replaced with the newer one.
 *
 * @param is//from  ww w  .  j a va 2s.  c o m
 *
 * @throws IOException
 */
public void loadAndReplaceMimetypes(InputStream is) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = null;

    while ((line = br.readLine()) != null) {
        line = line.trim();

        if (line.startsWith("#") || line.length() == 0) {
            // Ignore comments and empty lines.
        } else {
            StringTokenizer st = new StringTokenizer(line, " \t");
            if (st.countTokens() > 1) {
                String mimetype = st.nextToken();
                while (st.hasMoreTokens()) {
                    String extension = st.nextToken();
                    extensionToMimetypeMap.put(extension.toLowerCase(), mimetype);
                    if (log.isDebugEnabled()) {
                        log.debug("Setting mime type for extension '" + extension.toLowerCase() + "' to '"
                                + mimetype + "'");
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Ignoring mimetype with no associated file extensions: '" + line + "'");
                }
            }
        }
    }
}

From source file:org.gvnix.service.roo.addon.addon.util.WsdlParserUtils.java

/**
 * Method makePackageName./*from  ww w . ja  v a2s  .  c  o  m*/
 * 
 * @param namespace
 * @return
 */
public static String makePackageName(String namespace) {

    String hostname = null;
    String path = "";

    // get the target namespace of the document
    try {

        URL u = new URL(namespace);
        hostname = u.getHost();
        path = u.getPath();

    } catch (MalformedURLException e) {

        if (namespace.indexOf(':') > -1) {

            hostname = namespace.substring(namespace.indexOf(':') + 1);
            if (hostname.indexOf('/') > -1) {

                hostname = hostname.substring(0, hostname.indexOf('/'));
            }
        } else {

            hostname = namespace;
        }
    }

    // if we didn't file a hostname, bail
    if (hostname == null) {
        return null;
    }

    // convert illegal java identifier
    hostname = hostname.replace('-', '_');
    path = path.replace('-', '_');

    // chomp off last forward slash in path, if necessary
    if ((path.length() > 0) && (path.charAt(path.length() - 1) == '/')) {
        path = path.substring(0, path.length() - 1);
    }

    // tokenize the hostname and reverse it
    StringTokenizer st = new StringTokenizer(hostname, ".:");
    String[] words = new String[st.countTokens()];

    for (int i = 0; i < words.length; ++i) {
        words[i] = st.nextToken();
    }

    StringBuffer sb = new StringBuffer(namespace.length());

    for (int i = words.length - 1; i >= 0; --i) {
        addWordToPackageBuffer(sb, words[i], (i == words.length - 1));
    }

    // tokenize the path
    StringTokenizer st2 = new StringTokenizer(path, "/");

    while (st2.hasMoreTokens()) {
        addWordToPackageBuffer(sb, st2.nextToken(), false);
    }

    return sb.toString();
}

From source file:com.cisco.dvbu.ps.deploytool.ant.CompositeAntTask.java

private String[] getArgumentsArray() {
    if (arguments != null && arguments.trim().length() > 0) {
        StringTokenizer st = new StringTokenizer(arguments, getDelimiterString());

        String[] args = new String[st.countTokens() + 1];
        args[0] = getAction();// w ww.  j  a va 2  s.c o m
        int i = 1;

        while (st.hasMoreTokens()) {
            args[i] = st.nextToken().trim();
            i++;
        }
        return args;
    }
    return null;
}

From source file:net.servicefixture.parser.ExpressionTreeParser.java

public void addDataRow(Parse[] dataCells) {
    if ((dataCells.length != 2 && dataCells.length != 3) || StringUtils.isEmpty(dataCells[0].text())
            || StringUtils.isEmpty(dataCells[1].text())) {
        throw new ServiceFixtureException("The data row must and only have 2 or 3 non-blank data cells.");
    }//from   w  w  w.  j  a  va  2  s .c  o  m
    String expression = dataCells[0].text();

    StringTokenizer tokenizer = new StringTokenizer(expression, EXPRESSION_DELIMITER);

    Group group = tree.getRoot();
    //Creates group nodes
    while (tokenizer.countTokens() > 1) {
        group = getOrCreateGroupByName(group, tokenizer.nextToken());
    }
    //Now let's handle the last token which represents the leaf with value
    //or object type.
    String value = dataCells[1].text();

    if (value.startsWith(CLASS_TYPE_PREFIX) && value.endsWith(CLASS_TYPE_SUFFIX)) {
        //It is row that contains customized object type.
        String clazzName = value.substring(CLASS_TYPE_PREFIX.length(),
                value.length() - CLASS_TYPE_SUFFIX.length());
        Node node = null;
        if (dataCells.length == 3) {
            //It is the lowest level object with customized object type.
            node = new Leaf(tokenizer.nextToken(), dataCells[2]);
        } else {
            node = new Group(tokenizer.nextToken());
        }
        node.setObjectType(ReflectionUtils.newClass(clazzName));
        group.addChild(node);
    } else {
        Leaf leaf = new Leaf(tokenizer.nextToken(), dataCells[1]);
        group.addChild(leaf);
    }
}