Java Code Examples for java.util.StringTokenizer#hasMoreElements()

The following examples show how to use java.util.StringTokenizer#hasMoreElements() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ToolTipManagerEx.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Dimension parseDimension(String s) {
    StringTokenizer st = new StringTokenizer(s, ","); // NOI18N

    int arr[] = new int[2];
    int i = 0;
    while (st.hasMoreElements()) {
        if (i > 1) {
            return null;
        }
        try {
            arr[i] = Integer.parseInt(st.nextToken());
        } catch (NumberFormatException nfe) {
            LOG.log(Level.WARNING, null, nfe);
            return null;
        }
        i++;
    }
    if (i != 2) {
        return null;
    } else {
        return new Dimension(arr[0], arr[1]);
    }
}
 
Example 2
Source File: IterateWeirdness.java    From demo-java-x with MIT License 6 votes vote down vote up
public void withStreamIterate() {
	System.out.println("STREAM ITERATE");
	StringTokenizer tokens = createTokenizer();

	Object seed = tokens.nextElement();
	Predicate<Object> predicate = element -> {
		System.out.println("has more: " + tokens.hasMoreElements());
		return tokens.hasMoreElements();
	};
	UnaryOperator<Object> operator = element -> {
		System.out.println("ask for next");
		return tokens.nextElement();
	};

	Stream.iterate(seed, predicate, operator).forEach(el -> System.out.println("body: " + el));
}
 
Example 3
Source File: RuntimeExec.java    From alfresco-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * A comma or space separated list of values that, if returned by the executed command,
 * indicate an error value.  This defaults to <b>"1, 2"</b>.
 * 
 * @param errCodesStr the error codes for the execution
 */
public void setErrorCodes(String errCodesStr)
{
    errCodes.clear();
    StringTokenizer tokenizer = new StringTokenizer(errCodesStr, " ,");
    while(tokenizer.hasMoreElements())
    {
        String errCodeStr = tokenizer.nextToken();
        // attempt to convert it to an integer
        try
        {
            int errCode = Integer.parseInt(errCodeStr);
            this.errCodes.add(errCode);
        }
        catch (NumberFormatException e)
        {
            throw new AlfrescoRuntimeException(
                    "Property 'errorCodes' must be comma-separated list of integers: " + errCodesStr);
        }
    }
}
 
Example 4
Source File: StringUtil.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Splits a comma separated list of integers to integer list.
 * <p>
 * If an input is malformed, it is omitted from the result.
 *
 * @param input Comma separated list of integers.
 * @return A List containing the integers or null if the input is null.
 */
@Nullable
public static List<Integer> splitToIntList(@Nullable String input) {
    if (input == null) {
        return null;
    }
    List<Integer> result = new ArrayList<>();
    StringTokenizer tokenizer = new StringTokenizer(input, ",");
    while (tokenizer.hasMoreElements()) {
        final String item = tokenizer.nextToken();
        try {
            result.add(Integer.parseInt(item));
        } catch (NumberFormatException ex) {
            Log.e("ROOM", "Malformed integer list", ex);
        }
    }
    return result;
}
 
Example 5
Source File: BlockedTaskIdsParser.java    From workspacemechanic with Eclipse Public License 1.0 6 votes vote down vote up
public final List<String> parse(String text) {
  if (text == null) {
    return Collections.emptyList();
  }

  List<String> list = Lists.newArrayList();
  if (!text.startsWith("[")) {
    // I would use Splitter, but I won't use split.
    StringTokenizer st = new StringTokenizer(text, File.pathSeparator);
    while (st.hasMoreElements()) {
      list.add((String) st.nextElement());
    }
  } else {
    // TODO(konigsberg): There's got to be a way to get GSON to 
    // parse the string as a list, I'm just not interested right now.
    for (String entry : gson.fromJson(text, String[].class)) {
      list.add(entry);
    }
  }
  return list;
}
 
Example 6
Source File: Headers.java    From Kalle with Apache License 2.0 6 votes vote down vote up
/**
 * A value of the header information.
 *
 * @param content      like {@code text/html;charset=utf-8}.
 * @param key          like {@code charset}.
 * @param defaultValue list {@code utf-8}.
 * @return If you have a value key, you will return the parsed value if you don't return the default value.
 */
public static String parseSubValue(String content, String key, String defaultValue) {
    if (!TextUtils.isEmpty(content) && !TextUtils.isEmpty(key)) {
        StringTokenizer stringTokenizer = new StringTokenizer(content, ";");
        while (stringTokenizer.hasMoreElements()) {
            String valuePair = stringTokenizer.nextToken();
            int index = valuePair.indexOf('=');
            if (index > 0) {
                String name = valuePair.substring(0, index).trim();
                if (key.equalsIgnoreCase(name)) {
                    defaultValue = valuePair.substring(index + 1).trim();
                    break;
                }
            }
        }
    }
    return defaultValue;
}
 
Example 7
Source File: KhmerWordTokenizer.java    From modernmt with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> tokenize(final String text) {
    final List<String> tokens = new ArrayList<>();
    final StringTokenizer st = new StringTokenizer(text,
            "\u17D4\u17D5\u0020\u00A0\u115f\u1160\u1680"
                    + "\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007"
                    + "\u2008\u2009\u200A\u200B\u200c\u200d\u200e\u200f"
                    + "\u2028\u2029\u202a\u202b\u202c\u202d\u202e\u202f"
                    + "\u205F\u2060\u2061\u2062\u2063\u206A\u206b\u206c\u206d"
                    + "\u206E\u206F\u3000\u3164\ufeff\uffa0\ufff9\ufffa\ufffb"
                    + ",.;()[]{}«»!?:\"'’‘„“”…\\/\t\n", true);
    while (st.hasMoreElements()) {
        tokens.add(st.nextToken());
    }
    return tokens;
}
 
Example 8
Source File: TechServiceCreateProxyTask.java    From development with Apache License 2.0 5 votes vote down vote up
public List<String> getTagsFromString(String tags) {
    // Convert comma separated list into list
    StringTokenizer tok = new StringTokenizer(tags, ",");
    List<String> list = new ArrayList<String>();
    while (tok.hasMoreElements()) {
        String tagValue = tok.nextElement().toString().trim();
        if (tagValue.length() > 0)
            list.add(tagValue.trim());
    }
    return list;
}
 
Example 9
Source File: ProcessExecuter.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given command synchronously without timeout.
 * 
 * @return Retcode and stdout/stderr merged
 */
public Pair<Integer, String> exec(String command) throws IOException {
    StringTokenizer tok = new StringTokenizer(command);
    List<String> tokens = new ArrayList<>();
    while (tok.hasMoreElements())
        tokens.add(tok.nextToken());
    return exec(tokens.toArray(new String[0]));
}
 
Example 10
Source File: Message.java    From jcurses with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static int getHeight(String label) {

		StringTokenizer tokenizer = new StringTokenizer(label,"\n");
		int result = 0;
		while (tokenizer.hasMoreElements()) {
			tokenizer.nextElement();
			result++;
		}
		return result;
	}
 
Example 11
Source File: Basic39.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String name = req.getParameter(FIELD_NAME);
    StringTokenizer tok = new StringTokenizer(name, "\t");
    while(tok.hasMoreElements()) {
        PrintWriter writer = resp.getWriter();        
        writer.println(tok.nextElement());              /* BAD */    
    }
}
 
Example 12
Source File: StringHelper.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String[] tokenizeToStringArray(String str, String seperators) {
    if (str == null)
        return new String[0];
    StringTokenizer tokenlizer = new StringTokenizer(str, seperators);
    List result = new ArrayList();

    while (tokenlizer.hasMoreElements()) {
        Object s = tokenlizer.nextElement();
        result.add(s);
    }
    return (String[]) result.toArray(new String[result.size()]);
}
 
Example 13
Source File: Parser.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * SAX2: Receive notification of a processing instruction.
 *       These require special handling for stylesheet PIs.
 */
public void processingInstruction(String name, String value) {
    // We only handle the <?xml-stylesheet ...?> PI
    if ((_target == null) && (name.equals("xml-stylesheet"))) {

        String href = null;    // URI of stylesheet found
        String media = null;   // Media of stylesheet found
        String title = null;   // Title of stylesheet found
        String charset = null; // Charset of stylesheet found

        // Get the attributes from the processing instruction
        StringTokenizer tokens = new StringTokenizer(value);
        while (tokens.hasMoreElements()) {
            String token = (String)tokens.nextElement();
            if (token.startsWith("href"))
                href = getTokenValue(token);
            else if (token.startsWith("media"))
                media = getTokenValue(token);
            else if (token.startsWith("title"))
                title = getTokenValue(token);
            else if (token.startsWith("charset"))
                charset = getTokenValue(token);
        }

        // Set the target to this PI's href if the parameters are
        // null or match the corresponding attributes of this PI.
        if ( ((_PImedia == null) || (_PImedia.equals(media))) &&
             ((_PItitle == null) || (_PImedia.equals(title))) &&
             ((_PIcharset == null) || (_PImedia.equals(charset))) ) {
            _target = href;
        }
    }
}
 
Example 14
Source File: ActiveApiServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a {@link StringTokenizer} into an @{link {@link Enumeration
 * <String>}.
 * 
 * @author [email protected] (Antonio Bello)
 */
private Enumeration<String> convertRawEnumerationToGeneric(final StringTokenizer tokens) {
  return new Enumeration<String>() {
    @Override
    public String nextElement() {
      return (String) tokens.nextElement();
    }

    @Override
    public boolean hasMoreElements() {
      return tokens.hasMoreElements();
    }
  };
}
 
Example 15
Source File: Box.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 5 votes vote down vote up
/** Parses the byte array expressed by a string. */
   public static byte[] parseByteArray(String value) {
if (value == null)
    return null;

       StringTokenizer token = new StringTokenizer(value);
       int count = token.countTokens();

       byte[] buf = new byte[count];
       int i = 0;
       while(token.hasMoreElements()) {
           buf[i++] = new Byte(token.nextToken()).byteValue();
       }
       return buf;
   }
 
Example 16
Source File: Font2DTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private String[] parseUserText( String orig ) {
    int length = orig.length();
    StringTokenizer perLine = new StringTokenizer( orig, "\n" );
    String textLines[] = new String[ perLine.countTokens() ];
    int lineNumber = 0;

    while ( perLine.hasMoreElements() ) {
        StringBuffer converted = new StringBuffer();
        String oneLine = perLine.nextToken();
        int lineLength = oneLine.length();
        int prevEscapeEnd = 0;
        int nextEscape = -1;
        do {
            int nextBMPEscape = oneLine.indexOf( "\\u", prevEscapeEnd );
            int nextSupEscape = oneLine.indexOf( "\\U", prevEscapeEnd );
            nextEscape = (nextBMPEscape < 0)
                ? ((nextSupEscape < 0)
                   ? -1
                   : nextSupEscape)
                : ((nextSupEscape < 0)
                   ? nextBMPEscape
                   : Math.min(nextBMPEscape, nextSupEscape));

            if ( nextEscape != -1 ) {
                if ( prevEscapeEnd < nextEscape )
                    converted.append( oneLine.substring( prevEscapeEnd, nextEscape ));

                prevEscapeEnd = nextEscape + (nextEscape == nextBMPEscape ? 6 : 8);
                try {
                    String hex = oneLine.substring( nextEscape + 2, prevEscapeEnd );
                    if (nextEscape == nextBMPEscape) {
                        converted.append( (char) Integer.parseInt( hex, 16 ));
                    } else {
                        converted.append( new String( Character.toChars( Integer.parseInt( hex, 16 ))));
                    }
                }
                catch ( Exception e ) {
                    int copyLimit = Math.min(lineLength, prevEscapeEnd);
                    converted.append( oneLine.substring( nextEscape, copyLimit ));
                }
            }
        } while (nextEscape != -1);
        if ( prevEscapeEnd < lineLength )
          converted.append( oneLine.substring( prevEscapeEnd, lineLength ));
        textLines[ lineNumber++ ] = converted.toString();
    }
    return textLines;
}
 
Example 17
Source File: HttpConnector.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Pre-process the record.
 * 
 * @throws ComponentNotReadyException
 */
private void preProcessForRecord() throws ComponentNotReadyException {
	ignoredFieldsSet = extractIgnoredFields(ignoredFieldsToUse);

	// if (inputFieldNameToUse != null) {
	// inField = (StringDataField) getFieldSafe(inputRecord, inputFieldNameToUse);
	// if (inField == null) {
	// throw new ComponentNotReadyException("Unknown input field name '" + inputFieldNameToUse + "'.");
	// }
	// }
	//
	// // BACKWARD COMPATIBILITY: get the output field, where the content should be sent.
	// if (standardOutputRecord != null) {
	// if (outputFieldNameToUse == null) {
	// outField = (StringDataField) standardOutputRecord.getField(0);
	// } else {
	// outField = (StringDataField) getFieldSafe(standardOutputRecord, outputFieldNameToUse);
	// if (outField == null) {
	// throw new ComponentNotReadyException("Unknown output field name '" + outputFieldNameToUse + "'.");
	// }
	// }
	// }

	// create response writer based on the configuration
	if (outputFileUrlToUse != null) {
		responseWriter = new ResponseFileWriter(resultRecord != null ? resultRecord.getField(RP_OUTPUTFILE_INDEX) : null, outputFileUrlToUse);

	} else if (storeResponseToTempFileToUse) {
		responseWriter = new ResponseTempFileWriter(resultRecord != null ? resultRecord.getField(RP_OUTPUTFILE_INDEX) : null, temporaryFilePrefixToUse);

	} else {
		responseWriter = new ResponseByValueWriter(resultRecord != null ? resultRecord.getField(RP_CONTENT_INDEX) : null, resultRecord != null ? resultRecord.getField(RP_CONTENT_BYTE_INDEX) : null);
	}

	// filter multipart entities (ignored fields are removed from multipart entities record)
	if (!ignoredFieldsSet.isEmpty() && !StringUtils.isEmpty(multipartEntities)) {
		List<String> multipartEntitiesList = new ArrayList<String>();
		StringTokenizer tokenizer = new StringTokenizer(multipartEntities, ";");
		while (tokenizer.hasMoreElements()) {
			multipartEntitiesList.add(tokenizer.nextToken());
		}

		// remove ignored fields
		multipartEntitiesList.removeAll(ignoredFieldsSet);

		if (!multipartEntitiesList.isEmpty()) {
			multipartEntities = "";
			for (String entity : multipartEntitiesList) {
				multipartEntities += entity + ";";
			}
			multipartEntities = multipartEntities.substring(0, multipartEntities.length() - 1);
		} else {
			multipartEntities = null;
		}
	}
}
 
Example 18
Source File: SESConnector.java    From SensorWebClient with GNU General Public License v2.0 4 votes vote down vote up
private String[] getSingleObservations(ObservationPropertyType observations) {

        String obsPropType = observations.xmlText();
        
        // Determining how many observations are contained in the observation collection
        Pattern countPattern = Pattern.compile("<swe:value>(.*?)</swe:value>");
        Matcher countMatcher = countPattern.matcher(obsPropType);
        String countString = null;
        if (countMatcher.find()) {
            countString = countMatcher.group(1).trim();
        }
        int observationCount = Integer.parseInt(countString);

        // This array will contain one observation string for each observation of the observation
        // collection
        String[] outputStrings;

        // If the observation collection contains only one value it can be directly returned
        if (observationCount == 1) {
            outputStrings = new String[] {obsPropType};
        }

        // If the observation collection contains more than one value it must be split
        else {

            // Extracting the values that are contained in the observation collection and creating a
            // StringTokenizer that allows to access the values
            Pattern valuesPattern = Pattern.compile("<swe:values>(.*?)</swe:values>");
            Matcher valuesMatcher = valuesPattern.matcher(obsPropType);
            String valuesString = null;
            if (valuesMatcher.find()) {
                valuesString = valuesMatcher.group(1).trim();
            }

            StringTokenizer valuesTokenizer = new StringTokenizer(valuesString, ";");
            // If only the latest observation is wished, find youngest
            // observation.
            if (FeederConfig.getFeederConfig().isOnlyYoungestName()) {
                DateTime youngest = new DateTime(0);
                String youngestValues = "";
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                while (valuesTokenizer.hasMoreElements()) {
                    String valueString = (String) valuesTokenizer.nextElement();
                    DateTime time = fmt.parseDateTime(valueString.split(",")[0]);
                    if (time.isAfter(youngest.getMillis())) {
                        youngest = time;
                        youngestValues = valueString;
                    }
                }
                outputStrings = new String[] {createSingleObservationString(obsPropType, youngestValues)};
            }
            else {
                outputStrings = new String[observationCount];

                for (int i = 0; i < observationCount; i++) {

                    // Add the extracted observation to an array containing
                    // all extracted observations
                    outputStrings[i] = createSingleObservationString(obsPropType, valuesTokenizer.nextToken());
                }
            }

        }
        // Returning the extracted observations
        return outputStrings;
    }
 
Example 19
Source File: Font2DTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private String[] parseUserText( String orig ) {
    int length = orig.length();
    StringTokenizer perLine = new StringTokenizer( orig, "\n" );
    String textLines[] = new String[ perLine.countTokens() ];
    int lineNumber = 0;

    while ( perLine.hasMoreElements() ) {
        StringBuffer converted = new StringBuffer();
        String oneLine = perLine.nextToken();
        int lineLength = oneLine.length();
        int prevEscapeEnd = 0;
        int nextEscape = -1;
        do {
            int nextBMPEscape = oneLine.indexOf( "\\u", prevEscapeEnd );
            int nextSupEscape = oneLine.indexOf( "\\U", prevEscapeEnd );
            nextEscape = (nextBMPEscape < 0)
                ? ((nextSupEscape < 0)
                   ? -1
                   : nextSupEscape)
                : ((nextSupEscape < 0)
                   ? nextBMPEscape
                   : Math.min(nextBMPEscape, nextSupEscape));

            if ( nextEscape != -1 ) {
                if ( prevEscapeEnd < nextEscape )
                    converted.append( oneLine.substring( prevEscapeEnd, nextEscape ));

                prevEscapeEnd = nextEscape + (nextEscape == nextBMPEscape ? 6 : 8);
                try {
                    String hex = oneLine.substring( nextEscape + 2, prevEscapeEnd );
                    if (nextEscape == nextBMPEscape) {
                        converted.append( (char) Integer.parseInt( hex, 16 ));
                    } else {
                        converted.append( new String( Character.toChars( Integer.parseInt( hex, 16 ))));
                    }
                }
                catch ( Exception e ) {
                    int copyLimit = Math.min(lineLength, prevEscapeEnd);
                    converted.append( oneLine.substring( nextEscape, copyLimit ));
                }
            }
        } while (nextEscape != -1);
        if ( prevEscapeEnd < lineLength )
          converted.append( oneLine.substring( prevEscapeEnd, lineLength ));
        textLines[ lineNumber++ ] = converted.toString();
    }
    return textLines;
}
 
Example 20
Source File: JiraIssueCreation.java    From rice with Educational Community License v2.0 4 votes vote down vote up
@Test
    public void testCreateJira() throws InterruptedException, IOException {
        for (Map<String, String> jiraMap : jiraMaps.values()) {

            // Jira
            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("create_link"), this.getClass().toString());
            driver.get(jiraBase + "/secure/CreateIssue!default.jspa");

            // Project
            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("project-field"),
                    this.getClass().toString()).sendKeys(jiraMap.get("jira.project"));

            // Issue type
            WebElement issue = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id(
                    "issuetype-field"), this.getClass().toString());
            issue.click();
            issue.sendKeys(Keys.BACK_SPACE);
            issue.sendKeys(jiraMap.get("jira.issuetype"));
//            issue.sendKeys(Keys.ARROW_DOWN);
            issue.sendKeys(Keys.TAB);

            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("issue-create-submit"),
                    this.getClass().toString()).click();

            // Summary // TODO remove things that look like java object references
            // TODO if the error messages are the same for all jiras then include it in the summary
            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("summary"),
                    this.getClass().toString()).sendKeys(jiraMap.get("jira.summary"));

            // Components
            WebElement component = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id(
                    "components-textarea"), this.getClass().toString());
            String components = jiraMap.get("jira.component");
            StringTokenizer tokens = new StringTokenizer(components);
            while (tokens.hasMoreElements()) {
                component.click();
                component.sendKeys(tokens.nextToken());
//                component.sendKeys(Keys.ARROW_DOWN);
                component.sendKeys(Keys.TAB);
            }

            // Description
            WebElement descriptionElement = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("description"),
                    this.getClass().toString());
            descriptionElement.click();
            descriptionElement.sendKeys(jiraMap.get("jira.description"));

            // Priority
            WebElement priority = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("priority-field"),
                    this.getClass().toString());
            priority.click();
            priority.sendKeys(Keys.BACK_SPACE);
            priority.sendKeys(jiraMap.get("jira.priority"));
//            priority.sendKeys(Keys.ARROW_DOWN);
            priority.sendKeys(Keys.TAB);

            // Version
            WebElement version = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("versions-textarea"),
                    this.getClass().toString());
            version.click();
            version.sendKeys(jiraMap.get("jira.versions"));
//            version.sendKeys(Keys.ARROW_DOWN);
            version.sendKeys(Keys.TAB);

            // Fix version
            WebElement fixVersion = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("fixVersions-textarea"),
                    this.getClass().toString());
            fixVersion.click();
            fixVersion.sendKeys(jiraMap.get("jira.fixVersions"));
//            fixVersion.sendKeys(Keys.ARROW_DOWN);
            fixVersion.sendKeys(Keys.TAB);

            // Release notes unchecked
            WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("customfield_11621-1"),
                    this.getClass().toString()).click();

            WebDriverUtils.waitFor(driver, 8, By.id("issue-create-submit"), this.getClass().toString());

//            WebDriverUtils.acceptAlertIfPresent(driver); // Dialog present when running Se.....
        }
    }