java.util.StringTokenizer#countTokens ( )源码实例Demo

下面列出了java.util.StringTokenizer#countTokens ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: xipki   文件: CaCaps.java
public static CaCaps getInstance(String scepMessage) {
  CaCaps ret = new CaCaps();
  if (StringUtil.isBlank(scepMessage)) {
    return ret;
  }

  StringTokenizer st = new StringTokenizer(scepMessage, "\r\n");

  List<CaCapability> caps = new ArrayList<>(st.countTokens());
  while (st.hasMoreTokens()) {
    String token = st.nextToken();
    try {
      caps.add(CaCapability.forValue(token));
    } catch (IllegalArgumentException ex) {
      LOG.warn("ignore unknown CACap '{}'", token);
    }
  }

  if (!caps.isEmpty()) {
    ret.addCapabilities(caps.toArray(new CaCapability[0]));
  }

  return ret;
}
 
源代码2 项目: openjdk-8   文件: Supplementary.java
static void testTokenizer(String text, String delims, String[] expected) {
    StringTokenizer tokenizer = new StringTokenizer(text, delims);
    int n = tokenizer.countTokens();
    if (n != expected.length) {
        throw new RuntimeException("countToken(): wrong value " + n
                                   + ", expected " + expected.length);
    }
    int i = 0;
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if (!token.equals(expected[i++])) {
            throw new RuntimeException("nextToken(): wrong token. got \""
                                       + token + "\", expected \"" + expected[i-1]);
        }
    }
    if (i != expected.length) {
        throw new RuntimeException("unexpected the number of tokens: " + i
                                   + ", expected " + expected.length);
    }
}
 
源代码3 项目: openjdk-jdk9   文件: OperationFactory.java
public Object operate( Object value )
{
    StringTokenizer st = new StringTokenizer( getString( value ),
        sep ) ;
    int length = st.countTokens() ;
    Object result = null ;
    int ctr = 0 ;
    while (st.hasMoreTokens()) {
        String next = st.nextToken() ;
        Object val = act.operate( next ) ;
        if (result == null)
            result = Array.newInstance( val.getClass(), length ) ;
        Array.set( result, ctr++, val ) ;
    }

    return result ;
}
 
源代码4 项目: RDFS   文件: CommandExecutor.java
private static String[] getCommandAsArgs(final String cmd, final String masterKey,
                                       final String master) {
  StringTokenizer tokenizer = new StringTokenizer(cmd, " ");
  String[] args = new String[tokenizer.countTokens()];
  
  int i = 0;
  while (tokenizer.hasMoreTokens()) {
    args[i] = tokenizer.nextToken();

    args[i] = args[i].replaceAll(masterKey, master);
    args[i] = args[i].replaceAll("CLITEST_DATA", 
      new File(TestCLI.TEST_CACHE_DATA_DIR).
      toURI().toString().replace(' ', '+'));
    args[i] = args[i].replaceAll("USERNAME", System.getProperty("user.name"));

    i++;
  }
  
  return args;
}
 
源代码5 项目: jdk1.8-source-analysis   文件: Encodings.java
private String[] parseMimeTypes(String val) {
    int pos = val.indexOf(' ');
    //int lastPrintable;
    if (pos < 0) {
        // Maybe report/log this problem?
        //  "Last printable character not defined for encoding " +
        //  mimeName + " (" + val + ")" ...
        return new String[] { val };
        //lastPrintable = 0x00FF;
    }
    //lastPrintable =
    //    Integer.decode(val.substring(pos).trim()).intValue();
    StringTokenizer st =
            new StringTokenizer(val.substring(0, pos), ",");
    String[] values = new String[st.countTokens()];
    for (int i=0; st.hasMoreTokens(); i++) {
        values[i] = st.nextToken();
    }
    return values;
}
 
源代码6 项目: varsim   文件: StringUtilities.java
/**
 * split string into String array
 */
public static String[] fastSplit(final String s, final String delim) {
    StringTokenizer st = new StringTokenizer(s, delim);
    String[] result = new String[st.countTokens()];
    for (int i = 0; i < result.length; i++) {
        result[i] = st.nextToken();
    }
    return result;
}
 
源代码7 项目: pentaho-kettle   文件: EnvUtil.java
/**
 * Returns an available java.util.Locale object for the given localeCode.
 *
 * The localeCode code can be case insensitive, if it is available the method will find it and return it.
 *
 * @param localeCode
 * @return java.util.Locale.
 */
public static Locale createLocale( String localeCode ) {
  if ( Utils.isEmpty( localeCode ) ) {
    return null;
  }
  StringTokenizer parser = new StringTokenizer( localeCode, "_" );
  if ( parser.countTokens() == 2 ) {
    return new Locale( parser.nextToken(), parser.nextToken() );
  }
  if ( parser.countTokens() == 3 ) {
    return new Locale( parser.nextToken(), parser.nextToken(), parser.nextToken() );
  }
  return new Locale( localeCode );
}
 
源代码8 项目: dragonwell8_jdk   文件: MimeEntry.java
public synchronized void setExtensions(String extensionString) {
    StringTokenizer extTokens = new StringTokenizer(extensionString, ",");
    int numExts = extTokens.countTokens();
    String extensionStrings[] = new String[numExts];

    for (int i = 0; i < numExts; i++) {
        String ext = (String)extTokens.nextElement();
        extensionStrings[i] = ext.trim();
    }

    fileExtensions = extensionStrings;
}
 
/**
 * Checks that "content" string is valid.
 * If invalid a Datatype validation exception is thrown.
 *
 * @param content       the string value that needs to be validated
 * @param context       the validation context
 * @throws InvalidDatatypeException if the content is
 *         invalid according to the rules for the validators
 * @see InvalidDatatypeValueException
 */
public void validate(String content, ValidationContext context) throws InvalidDatatypeValueException {

    StringTokenizer parsedList = new StringTokenizer(content," ");
    int numberOfTokens =  parsedList.countTokens();
    if (numberOfTokens == 0) {
        throw new InvalidDatatypeValueException("EmptyList", null);
    }
    //Check each token in list against base type
    while (parsedList.hasMoreTokens()) {
        this.fItemValidator.validate(parsedList.nextToken(), context);
    }
}
 
private static Pattern getFilePattern(String filePatterns) {
	StringTokenizer tokenizer= new StringTokenizer(filePatterns, ","); //$NON-NLS-1$
	String[] filePatternArray= new String[tokenizer.countTokens()];
	int i= 0;
	while (tokenizer.hasMoreTokens()) {
		filePatternArray[i++]= tokenizer.nextToken().trim();
	}
	return PatternConstructor.createPattern(filePatternArray, true, false);
}
 
源代码11 项目: DeviceConnect-Android   文件: Scopes.java
public static String[] parseScope(String scopes) {
    if (scopes != null && scopes.length() > 0) {
        StringTokenizer st = new StringTokenizer(scopes, " ");
        String[] scope = new String[st.countTokens()];
        for (int i = 0; st.hasMoreTokens(); i++)
            scope[i] = st.nextToken();
        return scope;
    }
    return new String[0];
}
 
源代码12 项目: netbeans   文件: JavaSourceHelper.java
private static Tree createParameterizedTypeTree(WorkingCopy copy, String parameterizedType) {
    int left = parameterizedType.indexOf("<");
    int right = parameterizedType.lastIndexOf(">");
    String genericType = parameterizedType.substring(0, left);
    String types = parameterizedType.substring(left + 1, right);
    StringTokenizer tokenizer = new StringTokenizer(types, ",");
    String[] typeArgs = new String[tokenizer.countTokens()];
    int count = 0;
    while (tokenizer.hasMoreTokens()) {
        typeArgs[count++] = tokenizer.nextToken();
    }
    return createParameterizedTypeTree(copy, genericType, typeArgs);
}
 
源代码13 项目: scava   文件: NntpUtil.java
public static Article[] getArticleInfo(NNTPClient nntpClient,
		long startArticleNumber, long endArticleNumber) throws IOException {
	Reader reader = null;
	Article[] articles = null;
	reader = (DotTerminatedMessageReader) nntpClient.retrieveArticleInfo(
				startArticleNumber, endArticleNumber);

	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(Long.parseLong(stt.nextToken()));
			article.setSubject(decodeSubject(stt.nextToken()));
			article.setFrom(stt.nextToken());
			article.setDate(stt.nextToken());
			article.setArticleId(stt.nextToken());
			article.addReference(stt.nextToken());
			//article.addHeaderField("References", stt.nextToken());
			articles[index++] = article;
		}
	} else {
		return null;
	}

	return articles;
}
 
源代码14 项目: netbeans   文件: StrutsConfigUtilities.java
/** Returns all configuration files for the module
 **/
public static FileObject[] getConfigFiles(String module, FileObject dd){
    WebModule wm = WebModule.getWebModule(dd);
    if (wm == null)
        return null;
    FileObject docBase = wm.getDocumentBase();
    if (docBase == null)
        return null;
    Servlet servlet = getActionServlet(dd);
    InitParam param = null;
    if (module.equals(DEFAULT_MODULE_NAME))
        param = (InitParam)servlet.findBeanByName("InitParam", "ParamName", DEFAULT_MODULE_NAME);
    else
        param = (InitParam)servlet.findBeanByName("InitParam", "ParamName", DEFAULT_MODULE_NAME+"/"+module);
    FileObject[] configs = null;
    if (param != null){
        StringTokenizer st = new StringTokenizer(param.getParamValue(), ",");
        configs = new FileObject[st.countTokens()];
        int index = 0;
        while (st.hasMoreTokens()){
            String name = st.nextToken().trim();
            configs[index] = docBase.getFileObject(name);
            index++;
        }
    }
    return configs;
}
 
源代码15 项目: pcgen   文件: TempValueLst.java
@Override
protected ParseResult parseTokenWithSeparator(LoadContext context, CDOMObject obj, String value)
{
	int pipeLoc = value.indexOf(Constants.PIPE);
	if (pipeLoc == -1)
	{
		return new ParseResult.Fail(getTokenName() + " must have three | delimited arguments : " + value);
	}
	StringTokenizer tok = new StringTokenizer(value, Constants.PIPE);
	if (tok.countTokens() != 3)
	{
		return new ParseResult.Fail(getTokenName() + " requires three arguments, MIN=, MAX= and TITLE= : " + value);
	}
	if (!tok.nextToken().startsWith("MIN="))
	{
		return new ParseResult.Fail(getTokenName() + " first argument was not MIN=");
	}
	if (!tok.nextToken().startsWith("MAX="))
	{
		return new ParseResult.Fail(getTokenName() + " second argument was not MAX=");
	}
	if (!tok.nextToken().startsWith("TITLE="))
	{
		return new ParseResult.Fail(getTokenName() + " third argument was not TITLE=");
	}
	context.getObjectContext().put(obj, StringKey.TEMPVALUE, value);
	return ParseResult.SUCCESS;
}
 
源代码16 项目: gemfirexd-oss   文件: SystemProcedures.java
/**
 * Map SQLTables to EmbedDatabaseMetaData.getSchemas, getCatalogs,
 * getTableTypes and getTables, and return the result of the
 * DatabaseMetaData calls.
 *
 * <p>JCC and DNC overload this method:
 * <ul>
 * <li>If options contains the string 'GETSCHEMAS=1',
 *     call getSchemas()</li>
 * <li>If options contains the string 'GETSCHEMAS=2',
 *     call getSchemas(String, String)</li>
 * <li>If options contains the string 'GETCATALOGS=1',
 *     call getCatalogs()</li>
 * <li>If options contains the string 'GETTABLETYPES=1',
 *     call getTableTypes()</li>
 * <li>otherwise, call getTables()</li>
 * </ul>
 *
 *  @param catalogName SYSIBM.SQLTables CatalogName varchar(128),
 *  @param schemaName  SYSIBM.SQLTables SchemaName  varchar(128),
 *  @param tableName   SYSIBM.SQLTables TableName   varchar(128),
 *  @param tableType   SYSIBM.SQLTables TableType   varchar(4000))
 *  @param options     SYSIBM.SQLTables Options     varchar(4000))
 *  @param rs          output parameter, the resultset object 
 */
public static void SQLTABLES (String catalogName, String schemaName, String tableName,
									String tableType, String options, ResultSet[] rs)
	throws SQLException
{

	String optionValue = getOption("GETCATALOGS", options);
	if (optionValue != null && optionValue.trim().equals("1"))
	{
		rs[0] = getDMD().getCatalogs();
		return;
	}
	optionValue = getOption("GETTABLETYPES", options);
	if (optionValue != null && optionValue.trim().equals("1"))
	{
		rs[0] = getDMD().getTableTypes();
		return;
	}
	optionValue = getOption("GETSCHEMAS", options);
	if (optionValue != null) {
		optionValue = optionValue.trim();
		if (optionValue.equals("1")) {
			rs[0] = getDMD().getSchemas();
			return;
		}
		if (optionValue.equals("2")) {
			EmbedDatabaseMetaData edmd = (EmbedDatabaseMetaData) getDMD();
			rs[0] = edmd.getSchemas(catalogName, schemaName);
			return;
		}
	}
		 	

	String[] typeArray = null;
	if (tableType != null)
	{
		StringTokenizer st = new StringTokenizer(tableType,"',");
		typeArray = new String[st.countTokens()];
		int i = 0;

		while (st.hasMoreTokens()) 
		{
			typeArray[i] = st.nextToken();
			i++;
		}
	}
	rs[0] = getDMD().getTables(catalogName, schemaName, tableName, typeArray);
}
 
源代码17 项目: wasindoor   文件: svm_train.java
private void read_problem() throws IOException
{
	BufferedReader fp = new BufferedReader(new FileReader(input_file_name));
	Vector<Double> vy = new Vector<Double>();
	Vector<svm_node[]> vx = new Vector<svm_node[]>();
	int max_index = 0;

	while(true)
	{
		String line = fp.readLine();
		if(line == null) break;

		StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");

		vy.addElement(atof(st.nextToken()));
		int m = st.countTokens()/2;
		svm_node[] x = new svm_node[m];
		for(int j=0;j<m;j++)
		{
			x[j] = new svm_node();
			x[j].index = atoi(st.nextToken());
			x[j].value = atof(st.nextToken());
		}
		if(m>0) max_index = Math.max(max_index, x[m-1].index);
		vx.addElement(x);
	}

	prob = new svm_problem();
	prob.l = vy.size();
	prob.x = new svm_node[prob.l][];
	for(int i=0;i<prob.l;i++)
		prob.x[i] = vx.elementAt(i);
	prob.y = new double[prob.l];
	for(int i=0;i<prob.l;i++)
		prob.y[i] = vy.elementAt(i);

	if(param.gamma == 0 && max_index > 0)
		param.gamma = 1.0/max_index;

	if(param.kernel_type == svm_parameter.PRECOMPUTED)
		for(int i=0;i<prob.l;i++)
		{
			if (prob.x[i][0].index != 0)
			{
				System.err.print("Wrong kernel matrix: first column must be 0:sample_serial_number\n");
				System.exit(1);
			}
			if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)
			{
				System.err.print("Wrong input format: sample_serial_number out of range\n");
				System.exit(1);
			}
		}

	fp.close();
}
 
源代码18 项目: mantis   文件: ResourceUsagePayloadSetter.java
public ResourceUsagePayloadSetter(Heartbeat heartbeat, WorkerConfiguration config, String workerName, double networkMbps) {
    this.heartbeat = heartbeat;
    this.workerName = workerName;
    this.nwBytesLimit = networkMbps * 1024.0 * 1024.0 / 8.0; // convert from bits to bytes
    executor = new ScheduledThreadPoolExecutor(1);
    StringTokenizer tokenizer = new StringTokenizer(defaultReportingSchedule, ",");
    reportingIntervals = new long[tokenizer.countTokens()];
    int t = 0;
    while (tokenizer.hasMoreTokens()) {
        reportingIntervals[t++] = Long.parseLong(tokenizer.nextToken());
    }
    resourceUsageUtils = new MesosResourceUsageUtils(config.getMesosSlavePort());
    Metrics m = new Metrics.Builder()
            .name("ResourceUsage")
            .addGauge(cpuLimitGaugeName)
            .addGauge(cpuUsageCurrGaugeName)
            .addGauge(cpuUsagePeakGaugeName)
            .addGauge(memLimitGaugeName)
            .addGauge(cachedMemUsageCurrGaugeName)
            .addGauge(cachedMemUsagePeakGaugeName)
            .addGauge(totMemUsageCurrGaugeName)
            .addGauge(totMemUsagePeakGaugeName)
            .addGauge(nwBytesLimitGaugeName)
            .addGauge(nwBytesUsageCurrGaugeName)
            .addGauge(nwBytesUsagePeakGaugeName)
            .addGauge(jvmMemoryUsedGaugeName)
            .addGauge(jvmMemoryMaxGaugeName)
            .build();
    m = MetricsRegistry.getInstance().registerAndGet(m);
    cpuLimitGauge = m.getGauge(cpuLimitGaugeName);
    cpuUsageCurrGauge = m.getGauge(cpuUsageCurrGaugeName);
    cpuUsagePeakGauge = m.getGauge(cpuUsagePeakGaugeName);
    memLimitGauge = m.getGauge(memLimitGaugeName);
    cachedMemUsageCurrGauge = m.getGauge(cachedMemUsageCurrGaugeName);
    cachedMemUsagePeakGauge = m.getGauge(cachedMemUsagePeakGaugeName);
    totMemUsageCurrGauge = m.getGauge(totMemUsageCurrGaugeName);
    totMemUsagePeakGauge = m.getGauge(totMemUsagePeakGaugeName);
    nwBytesLimitGauge = m.getGauge(nwBytesLimitGaugeName);
    nwBytesUsageCurrGauge = m.getGauge(nwBytesUsageCurrGaugeName);
    nwBytesUsagePeakGauge = m.getGauge(nwBytesUsagePeakGaugeName);
    jvmMemoryUsedGauge = m.getGauge(jvmMemoryUsedGaugeName);
    jvmMemoryMaxGauge = m.getGauge(jvmMemoryMaxGaugeName);
}
 
源代码19 项目: cxf   文件: TestSOAPHandler.java
private boolean getReturnValue(boolean outbound, SOAPMessageContext ctx) {
    boolean ret = true;
    try {
        SOAPMessage msg = ctx.getMessage();
        SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();

        if (body.getFirstChild().getFirstChild() == null) {
            return true;
        }

        Node commandNode = body.getFirstChild().getFirstChild().getFirstChild();
        String arg = commandNode.getNodeValue();
        String namespace = body.getFirstChild().getFirstChild().getNamespaceURI();

        StringTokenizer strtok = new StringTokenizer(arg, " ");
        String hid = "";
        String direction = "";
        String command = "";
        if (strtok.countTokens() >= 3) {
            hid = strtok.nextToken();
            direction = strtok.nextToken();
            command = strtok.nextToken();
        }

        if (!getHandlerId().equals(hid)) {
            return true;
        }

        if ("stop".equals(command)) {
            if (!outbound && "inbound".equals(direction)) {
                 // remove the incoming request body.
                Document doc = body.getOwnerDocument();
                // build the SOAP response for this message
                //
                Node wrapper = doc.createElementNS(namespace, "pingResponse");
                wrapper.setPrefix("ns4");
                body.removeChild(body.getFirstChild());
                body.appendChild(wrapper);

                for (String info : getHandlerInfoList(ctx)) {
                    // copy the previously invoked handler list into the response.
                    // Ignore this handler's information as it will be added again later.
                    //
                    if (!info.contains(getHandlerId())) {
                        Node newEl = doc.createElementNS(namespace, "HandlersInfo");
                        newEl.setPrefix("ns4");
                        newEl.appendChild(doc.createTextNode(info));
                        wrapper.appendChild(newEl);
                    }
                }
                ret = false;
            } else if (outbound && "outbound".equals(direction)) {
                ret = false;
            }
        } else if ("throw".equals(command)) {
            String exceptionType = null;
            String exceptionText = "HandleMessage throws exception";
            if (strtok.hasMoreTokens()) {
                exceptionType = strtok.nextToken();
            }
            if (strtok.hasMoreTokens()) {
                exceptionText = strtok.nextToken();
            }
            if (exceptionType != null && !outbound && "inbound".equals(direction)) {
                if ("RuntimeException".equals(exceptionType)) {
                    throw new RuntimeException(exceptionText);
                } else if ("ProtocolException".equals(exceptionType)) {
                    throw new ProtocolException(exceptionText);
                } else if ("SOAPFaultException".equals(exceptionType)) {
                    throw createSOAPFaultException(exceptionText);
                } else if ("SOAPFaultExceptionWDetail".equals(exceptionType)) {
                    throw createSOAPFaultExceptionWithDetail(exceptionText);
                }
            } else if (exceptionType != null && outbound && "outbound".equals(direction)) {
                if ("RuntimeException".equals(exceptionType)) {
                    throw new RuntimeException(exceptionText);
                } else if ("ProtocolException".equals(exceptionType)) {
                    throw new ProtocolException(exceptionText);
                } else if ("SOAPFaultException".equals(exceptionType)) {
                    throw createSOAPFaultException(exceptionText);
                } else if ("SOAPFaultExceptionWDetail".equals(exceptionType)) {
                    throw createSOAPFaultExceptionWithDetail(exceptionText);
                }
            }

        }

    } catch (SOAPException e) {
        e.printStackTrace();
    }

    return ret;
}
 
源代码20 项目: drftpd   文件: IpSecurityHooks.java
@CommandHook(commands = "doSITE_SLAVE", type = HookType.PRE)
public CommandRequestInterface doIpSecuritySLAVEPreCheck(CommandRequest request) {
    if (!request.hasArgument()) {
        return request;
    }

    String argument = request.getArgument();
    StringTokenizer arguments = new StringTokenizer(argument);

    if (!arguments.hasMoreTokens()) {
        return request;
    }

    String slavename = arguments.nextToken();

    RemoteSlave rslave;
    try {
        rslave = GlobalContext.getGlobalContext().getSlaveManager().getRemoteSlave(slavename);
    } catch (ObjectNotFoundException e) {
        request.setDeniedResponse(new CommandResponse(200, "Slave Not Found: " + slavename));
        request.setAllowed(false);
        return request;
    }

    if (arguments.hasMoreTokens()) {
        String command = arguments.nextToken();
        if (command.equalsIgnoreCase("addmask")) {
            if (arguments.countTokens() != 1) {
                return request;
            }

            HostMask newMask = new HostMask(arguments.nextToken().replace(",", ""));

            String _maskident = newMask.getIdentMask();
            String _maskHostMask = newMask.getHostMask();

            boolean _allowed = IpSecurityManager.getIpSecurity().checkIP(_maskident, _maskHostMask, rslave.getMasks().size(), null);
            if ((!_allowed) && (!_maskHostMask.equals("127.0.0.1"))) {
                request.setAllowed(false);
                CommandResponse response = StandardCommandManager.genericResponse("RESPONSE_200_COMMAND_OK");
                response.addComment(IpSecurityManager.getIpSecurity().outputConfs(null));
                request.setDeniedResponse(response);
                return request;
            }
        }
    }
    return request;
}