Java Code Examples for java.text.CharacterIterator#DONE

The following examples show how to use java.text.CharacterIterator#DONE . 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: SwingUtilities2.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private static AttributedCharacterIterator getTrimmedTrailingSpacesIterator
        (AttributedCharacterIterator iterator) {
    int curIdx = iterator.getIndex();

    char c = iterator.last();
    while(c != CharacterIterator.DONE && Character.isWhitespace(c)) {
        c = iterator.previous();
    }

    if (c != CharacterIterator.DONE) {
        int endIdx = iterator.getIndex();

        if (endIdx == iterator.getEndIndex() - 1) {
            iterator.setIndex(curIdx);
            return iterator;
        } else {
            AttributedString trimmedText = new AttributedString(iterator,
                    iterator.getBeginIndex(), endIdx + 1);
            return trimmedText.getIterator();
        }
    } else {
        return null;
    }
}
 
Example 2
Source File: WhitespaceBasedBreakIterator.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate break positions eagerly parallel to reading text.
 */
public void setText(CharacterIterator ci) {
    int begin = ci.getBeginIndex();
    text = new char[ci.getEndIndex() - begin];
    int[] breaks0 = new int[text.length + 1];
    int brIx = 0;
    breaks0[brIx++] = begin;

    int charIx = 0;
    boolean inWs = false;
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        text[charIx] = c;
        boolean ws = Character.isWhitespace(c);
        if (inWs && !ws) {
            breaks0[brIx++] = charIx + begin;
        }
        inWs = ws;
        charIx++;
    }
    if (text.length > 0) {
        breaks0[brIx++] = text.length + begin;
    }
    System.arraycopy(breaks0, 0, breaks = new int[brIx], 0, brIx);
}
 
Example 3
Source File: JSONValidator.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
private boolean literal(String text) {
    CharacterIterator ci = new StringCharacterIterator(text);
    char t = ci.first();
    if (c != t) { return false; }

    int start = col;
    boolean ret = true;
    for (t = ci.next(); t != CharacterIterator.DONE; t = ci.next()) {
        if (t != nextCharacter()) {
            ret = false;
            break;
        }
    }
    nextCharacter();

    if (!ret) { error("literal " + text, start); }
    return ret;
}
 
Example 4
Source File: JsonValidatorUtil.java    From xiaoV with GNU General Public License v3.0 6 votes vote down vote up
private boolean valid(String input) {
	if ("".equals(input))
		return true;

	boolean ret = true;
	it = new StringCharacterIterator(input);
	c = it.first();
	col = 1;
	if (!value()) {
		ret = error("value", 1);
	} else {
		skipWhiteSpace();
		if (c != CharacterIterator.DONE) {
			ret = error("end", col);
		}
	}

	return ret;
}
 
Example 5
Source File: WhitespaceBasedBreakIterator.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculate break positions eagerly parallel to reading text.
 */
public void setText(CharacterIterator ci) {
    int begin = ci.getBeginIndex();
    text = new char[ci.getEndIndex() - begin];
    int[] breaks0 = new int[text.length + 1];
    int brIx = 0;
    breaks0[brIx++] = begin;

    int charIx = 0;
    boolean inWs = false;
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        text[charIx] = c;
        boolean ws = Character.isWhitespace(c);
        if (inWs && !ws) {
            breaks0[brIx++] = charIx + begin;
        }
        inWs = ws;
        charIx++;
    }
    if (text.length > 0) {
        breaks0[brIx++] = text.length + begin;
    }
    System.arraycopy(breaks0, 0, breaks = new int[brIx], 0, brIx);
}
 
Example 6
Source File: TextLine.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * When this returns, the ACI's current position will be at the start of the
 * first run which does NOT contain a GraphicAttribute.  If no such run exists
 * the ACI's position will be at the end, and this method will return false.
 */
static boolean advanceToFirstFont(AttributedCharacterIterator aci) {

    for (char ch = aci.first();
         ch != CharacterIterator.DONE;
         ch = aci.setIndex(aci.getRunLimit()))
    {

        if (aci.getAttribute(TextAttribute.CHAR_REPLACEMENT) == null) {
            return true;
        }
    }

    return false;
}
 
Example 7
Source File: CharacterIteratorWrapper.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @see UCharacterIterator#current()
 */
public int current() {
    int c = iterator.current();
    if(c==CharacterIterator.DONE){
      return DONE;
    }
    return c;
}
 
Example 8
Source File: AttributedStringTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.text.AttributedString#AttributedString(java.lang.String)
 */
public void test_ConstructorLjava_lang_String() {
	String test = "Test string";
	AttributedString attrString = new AttributedString(test);
	AttributedCharacterIterator it = attrString.getIterator();
	StringBuffer buf = new StringBuffer();
	buf.append(it.first());
	char ch;
	while ((ch = it.next()) != CharacterIterator.DONE)
		buf.append(ch);
	assertTrue("Wrong string: " + buf, buf.toString().equals(test));
}
 
Example 9
Source File: AttributedStringTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, Set keys, int[] expectedLimits) throws Exception {
    int previous = 0;
    char c = iterator.first();
    for (int i = 0; i < expectedLimits.length; i++) {
         if (iterator.getRunStart(keys) != previous || iterator.getRunLimit(keys) != expectedLimits[i]) {
             throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart(keys) + ", " + iterator.getRunLimit(keys) + " for keys " + keys);
         }
         previous = expectedLimits[i];
         c = iterator.setIndex(previous);
    }
    if (c != CharacterIterator.DONE) {
        throwException(iterator, "iterator's run sequence doesn't end with DONE");
    }
}
 
Example 10
Source File: Text.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * For the given string, returns the number of UTF-8 bytes
 * required to encode the string.
 * @param string text to encode
 * @return number of UTF-8 bytes required to encode
 */
public static int utf8Length(String string) {
  CharacterIterator iter = new StringCharacterIterator(string);
  char ch = iter.first();
  int size = 0;
  while (ch != CharacterIterator.DONE) {
    if ((ch >= 0xD800) && (ch < 0xDC00)) {
      // surrogate pair?
      char trail = iter.next();
      if ((trail > 0xDBFF) && (trail < 0xE000)) {
        // valid pair
        size += 4;
      } else {
        // invalid pair
        size += 3;
        iter.previous(); // rewind one
      }
    } else if (ch < 0x80) {
      size++;
    } else if (ch < 0x800) {
      size += 2;
    } else {
      // ch < 0x10000, that is, the largest char value
      size += 3;
    }
    ch = iter.next();
  }
  return size;
}
 
Example 11
Source File: StringRecord.java    From stratosphere with Apache License 2.0 5 votes vote down vote up
/**
 * For the given string, returns the number of UTF-8 bytes required to
 * encode the string.
 * 
 * @param string
 *        text to encode
 * @return number of UTF-8 bytes required to encode
 */
public static int utf8Length(final String string) {
	final CharacterIterator iter = new StringCharacterIterator(string);
	char ch = iter.first();
	int size = 0;
	while (ch != CharacterIterator.DONE) {
		if ((ch >= 0xD800) && (ch < 0xDC00)) {
			// surrogate pair?
			char trail = iter.next();
			if ((trail > 0xDBFF) && (trail < 0xE000)) {
				// valid pair
				size += 4;
			} else {
				// invalid pair
				size += 3;
				iter.previous(); // rewind one
			}
		} else if (ch < 0x80) {
			size++;
		} else if (ch < 0x800) {
			size += 2;
		} else {
			// ch < 0x10000, that is, the largest char value
			size += 3;
		}
		ch = iter.next();
	}
	return size;
}
 
Example 12
Source File: TextLayout.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a <code>TextLayout</code> from an iterator over styled text.
 * <p>
 * The iterator must specify a single paragraph of text because an
 * entire paragraph is required for the bidirectional
 * algorithm.
 * @param text the styled text to display
 * @param frc contains information about a graphics device which is needed
 *       to measure the text correctly.
 *       Text measurements can vary slightly depending on the
 *       device resolution, and attributes such as antialiasing.  This
 *       parameter does not specify a translation between the
 *       <code>TextLayout</code> and user space.
 */
public TextLayout(AttributedCharacterIterator text, FontRenderContext frc) {

    if (text == null) {
        throw new IllegalArgumentException("Null iterator passed to TextLayout constructor.");
    }

    int start = text.getBeginIndex();
    int limit = text.getEndIndex();
    if (start == limit) {
        throw new IllegalArgumentException("Zero length iterator passed to TextLayout constructor.");
    }

    int len = limit - start;
    text.first();
    char[] chars = new char[len];
    int n = 0;
    for (char c = text.first();
         c != CharacterIterator.DONE;
         c = text.next())
    {
        chars[n++] = c;
    }

    text.first();
    if (text.getRunLimit() == limit) {

        Map<? extends Attribute, ?> attributes = text.getAttributes();
        Font font = singleFont(chars, 0, len, attributes);
        if (font != null) {
            fastInit(chars, font, attributes, frc);
            return;
        }
    }

    standardInit(text, chars, frc);
}
 
Example 13
Source File: Text.java    From Canova with Apache License 2.0 5 votes vote down vote up
/**
 * For the given string, returns the number of UTF-8 bytes
 * required to encode the string.
 * @param string text to encode
 * @return number of UTF-8 bytes required to encode
 */
public static int utf8Length(String string) {
    CharacterIterator iter = new StringCharacterIterator(string);
    char ch = iter.first();
    int size = 0;
    while (ch != CharacterIterator.DONE) {
        if ((ch >= 0xD800) && (ch < 0xDC00)) {
            // surrogate pair?
            char trail = iter.next();
            if ((trail > 0xDBFF) && (trail < 0xE000)) {
                // valid pair
                size += 4;
            } else {
                // invalid pair
                size += 3;
                iter.previous(); // rewind one
            }
        } else if (ch < 0x80) {
            size++;
        } else if (ch < 0x800) {
            size += 2;
        } else {
            // ch < 0x10000, that is, the largest char value
            size += 3;
        }
        ch = iter.next();
    }
    return size;
}
 
Example 14
Source File: IMSC11ResourceConverterState.java    From ttt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void populateText(Paragraph p, AttributedString as, boolean insertBreakBefore, Direction blockDirection) {
    if (as != null) {
        List<Serializable> content = p.getContent();
        if (insertBreakBefore)
            content.add(ttmlFactory.createBr(ttmlFactory.createBreak()));
        AttributedCharacterIterator aci = as.getIterator();
        aci.first();
        StringBuffer sb = new StringBuffer();
        while (aci.current() != CharacterIterator.DONE) {
            int i = aci.getRunStart();
            int e = aci.getRunLimit();
            Map<AttributedCharacterIterator.Attribute,Object> attributes = aci.getAttributes();
            while (i < e) {
                sb.append(aci.setIndex(i++));
            }
            String text = sb.toString();
            if (!text.isEmpty()) {
                if (!attributes.isEmpty()) {
                    populateAttributedText(content, text, attributes, blockDirection);
                } else {
                    content.add(text);
                }
            }
            sb.setLength(0);
            aci.setIndex(e);
        }
    }
}
 
Example 15
Source File: Json.java    From jgroups-kubernetes with Apache License 2.0 5 votes vote down vote up
private void skipWhiteSpace()
{
   do
   {
      if (Character.isWhitespace(c))
         ;
      else if (c == '/')
      {
         next();
         if (c == '*')
         {
            // skip multiline comments
            while (c != CharacterIterator.DONE)
               if (next() == '*' && next() == '/')
                  break;
            if (c == CharacterIterator.DONE)
               throw new MalformedJsonException("Unterminated comment while parsing JSON string.");
         }
         else if (c == '/')
            while (c != '\n' && c != CharacterIterator.DONE)
               next();
         else
         {
            previous();
            break;
         }
      }
      else
         break;
   } while (next() != CharacterIterator.DONE);
}
 
Example 16
Source File: RuleBasedBreakIterator.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This method backs the iterator back up to a "safe position" in the text.
 * This is a position that we know, without any context, must be a break position.
 * The various calling methods then iterate forward from this safe position to
 * the appropriate position to return.  (For more information, see the description
 * of buildBackwardsStateTable() in RuleBasedBreakIterator.Builder.)
 */
protected int handlePrevious() {
    CharacterIterator text = getText();
    int state = START_STATE;
    int category = 0;
    int lastCategory = 0;
    int c = getCurrent();

    // loop until we reach the beginning of the text or transition to state 0
    while (c != CharacterIterator.DONE && state != STOP_STATE) {

        // save the last character's category and look up the current
        // character's category
        lastCategory = category;
        category = lookupCategory(c);

        // if the current character isn't an ignore character, look up a
        // state transition in the backwards state table
        if (category != IGNORE) {
            state = lookupBackwardState(state, category);
        }

        // then advance one character backwards
        c = getPrevious();
    }

    // if we didn't march off the beginning of the text, we're either one or two
    // positions away from the real break position.  (One because of the call to
    // previous() at the end of the loop above, and another because the character
    // that takes us into the stop state will always be the character BEFORE
    // the break position.)
    if (c != CharacterIterator.DONE) {
        if (lastCategory != IGNORE) {
            getNext();
            getNext();
        }
        else {
            getNext();
        }
    }
    return text.getIndex();
}
 
Example 17
Source File: CDateTime.java    From nebula with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * inspects all of the calendar fields in the <code>field</code> array to
 * determine what style is appropriate and then sets that style to the
 * picker using the setPickerStyle method.<br>
 */
private boolean updateFields() {
	Field[] bak = new Field[field == null ? 0 : field.length];
	if (bak.length > 0) {
		System.arraycopy(field, 0, bak, 0, field.length);
	}

	AttributedCharacterIterator aci = df
			.formatToCharacterIterator(calendar.getTime());
	field = new Field[aci.getAllAttributeKeys().size()];
	separator = new String[field.length + 1]; // there can be a separator
												// before and after
	int i = 0;
	Object last = null;
	for (char c = aci.first(); c != CharacterIterator.DONE; c = aci
			.next()) {
		Object[] oa = aci.getAttributes().keySet().toArray();
		if (oa.length > 0) {
			if (oa[0] != last && i < field.length) {
				if (getCalendarField((Field) oa[0]) < 0) {
					if (bak.length > 0) {
						field = new Field[bak.length];
						System.arraycopy(bak, 0, field, 0, bak.length);
					}
					return false;
				} else {
					field[i] = (Field) oa[0];
					last = oa[0];
				}
				i++;
			}
		} else {
			if (separator[i] == null) {
				separator[i] = String.valueOf(c);
			}
		}
	}

	df.setLenient(false);
	setActiveField(FIELD_NONE);
	return true;
}
 
Example 18
Source File: InputMethodEvent.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a parameter string identifying this event.
 * This method is useful for event-logging and for debugging.
 * It contains the event ID in text form, the characters of the
 * committed and composed text
 * separated by "+", the number of committed characters,
 * the caret, and the visible position.
 *
 * @return a string identifying the event and its attributes
 */
public String paramString() {
    String typeStr;
    switch(id) {
      case INPUT_METHOD_TEXT_CHANGED:
          typeStr = "INPUT_METHOD_TEXT_CHANGED";
          break;
      case CARET_POSITION_CHANGED:
          typeStr = "CARET_POSITION_CHANGED";
          break;
      default:
          typeStr = "unknown type";
    }

    String textString;
    if (text == null) {
        textString = "no text";
    } else {
        StringBuilder textBuffer = new StringBuilder("\"");
        int committedCharacterCount = this.committedCharacterCount;
        char c = text.first();
        while (committedCharacterCount-- > 0) {
            textBuffer.append(c);
            c = text.next();
        }
        textBuffer.append("\" + \"");
        while (c != CharacterIterator.DONE) {
            textBuffer.append(c);
            c = text.next();
        }
        textBuffer.append("\"");
        textString = textBuffer.toString();
    }

    String countString = committedCharacterCount + " characters committed";

    String caretString;
    if (caret == null) {
        caretString = "no caret";
    } else {
        caretString = "caret: " + caret.toString();
    }

    String visiblePositionString;
    if (visiblePosition == null) {
        visiblePositionString = "no visible position";
    } else {
        visiblePositionString = "visible position: " + visiblePosition.toString();
    }

    return typeStr + ", " + textString + ", " + countString + ", " + caretString + ", " + visiblePositionString;
}
 
Example 19
Source File: BirtResources.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Escapes a string to make it usable in JavaScript.
 * @param s input string
 * @return escaped string, without quotes
 */
public static String makeJavaScriptString( String s )
{
	StringBuffer output = new StringBuffer( s.length( ) );
	CharacterIterator it = new StringCharacterIterator(s);		
	for (char c = it.first(); c != CharacterIterator.DONE; c = it.next())
	{
		switch ( c )
		{
			// backspace
			case 0x08:
				output.append( BACKSLASH + "b" );
				break;
			// tab
			case 0x09:
				output.append( BACKSLASH + "t" );
				break;
			// newline
			case 0x0A:
				output.append( BACKSLASH + "n" );
				break;
			// form feed
			case 0x0C:
				output.append( BACKSLASH + "f" );
				break;
			// carriage return
			case 0x0D:
				output.append( BACKSLASH + "r" );
				break;
			// single quote
			case 0x27:
			// double quote
			case 0x22:
			// slash
			case 0x2F:
			// backslash
			case 0x5C:
				output.append( BACKSLASH + c );
				break;
			// string ranges
			default:
				output.append( c );
		}			
	}
	return output.toString();
}
 
Example 20
Source File: InputMethodContext.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Dispatches committed text to a client component.
 * Called by composition window.
 *
 * @param client The component that the text should get dispatched to.
 * @param text The iterator providing access to the committed
 *        (and possible composed) text.
 * @param committedCharacterCount The number of committed characters in the text.
 */
synchronized void dispatchCommittedText(Component client,
             AttributedCharacterIterator text,
             int committedCharacterCount) {
    // note that the client is not always the current client component -
    // some host input method adapters may dispatch input method events
    // through the Java event queue, and we may have switched clients while
    // the event was in the queue.
    if (committedCharacterCount == 0
            || text.getEndIndex() <= text.getBeginIndex()) {
        return;
    }
    long time = System.currentTimeMillis();
    dispatchingCommittedText = true;
    try {
        InputMethodRequests req = client.getInputMethodRequests();
        if (req != null) {
            // active client -> send text as InputMethodEvent
            int beginIndex = text.getBeginIndex();
            AttributedCharacterIterator toBeCommitted =
                (new AttributedString(text, beginIndex, beginIndex + committedCharacterCount)).getIterator();

            InputMethodEvent inputEvent = new InputMethodEvent(
                    client,
                    InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
                    toBeCommitted,
                    committedCharacterCount,
                    null, null);

            client.dispatchEvent(inputEvent);
        } else {
            // passive client -> send text as KeyEvents
            char keyChar = text.first();
            while (committedCharacterCount-- > 0 && keyChar != CharacterIterator.DONE) {
                KeyEvent keyEvent = new KeyEvent(client, KeyEvent.KEY_TYPED,
                                             time, 0, KeyEvent.VK_UNDEFINED, keyChar);
                client.dispatchEvent(keyEvent);
                keyChar = text.next();
            }
        }
    } finally {
        dispatchingCommittedText = false;
    }
}