Example usage for java.lang CharSequence subSequence

List of usage examples for java.lang CharSequence subSequence

Introduction

In this page you can find the example usage for java.lang CharSequence subSequence.

Prototype

CharSequence subSequence(int start, int end);

Source Link

Document

Returns a CharSequence that is a subsequence of this sequence.

Usage

From source file:com.eaio.util.text.HumanTime.java

/**
 * Parses a {@link CharSequence} argument and returns a {@link HumanTime} instance.
 * /*from  www  .  j  a va2 s.c o m*/
 * @param s the char sequence, may not be <code>null</code>
 * @return an instance, never <code>null</code>
 */
public static HumanTime eval(final CharSequence s) {
    HumanTime out = new HumanTime(0L);

    int num = 0;

    int start = 0;
    int end = 0;

    State oldState = State.IGNORED;

    for (char c : new Iterable<Character>() {

        /**
         * @see java.lang.Iterable#iterator()
         */
        public Iterator<Character> iterator() {
            return new Iterator<Character>() {

                private int p = 0;

                /**
                 * @see java.util.Iterator#hasNext()
                 */
                public boolean hasNext() {
                    return p < s.length();
                }

                /**
                 * @see java.util.Iterator#next()
                 */
                public Character next() {
                    return s.charAt(p++);
                }

                /**
                 * @see java.util.Iterator#remove()
                 */
                public void remove() {
                    throw new UnsupportedOperationException();
                }

            };
        }

    }) {
        State newState = getState(c);
        if (oldState != newState) {
            if (oldState == State.NUMBER && (newState == State.IGNORED || newState == State.UNIT)) {
                num = Integer.parseInt(s.subSequence(start, end).toString());
            } else if (oldState == State.UNIT && (newState == State.IGNORED || newState == State.NUMBER)) {
                out.nTimes(s.subSequence(start, end).toString(), num);
                num = 0;
            }
            start = end;
        }
        ++end;
        oldState = newState;
    }
    if (oldState == State.UNIT) {
        out.nTimes(s.subSequence(start, end).toString(), num);
    }

    return out;
}

From source file:net.opacapp.multilinecollapsingtoolbar.CollapsingTextHelper.java

private void calculateUsingTextSize(final float textSize) {
    if (mText == null)
        return;//  w w w .j  a v a 2  s . c  om
    final float availableWidth;
    final float newTextSize;
    boolean updateDrawText = false;
    // BEGIN MODIFICATION: Add maxLines variable
    int maxLines;
    // END MODIFICATION
    if (isClose(textSize, mCollapsedTextSize)) {
        availableWidth = mCollapsedBounds.width();
        newTextSize = mCollapsedTextSize;
        mScale = 1f;
        if (mCurrentTypeface != mCollapsedTypeface) {
            mCurrentTypeface = mCollapsedTypeface;
            updateDrawText = true;
        }
        // BEGIN MODIFICATION: Set maxLines variable
        maxLines = 1;
        // END MODIFICATION
    } else {
        availableWidth = mExpandedBounds.width();
        newTextSize = mExpandedTextSize;
        if (mCurrentTypeface != mExpandedTypeface) {
            mCurrentTypeface = mExpandedTypeface;
            updateDrawText = true;
        }
        if (isClose(textSize, mExpandedTextSize)) {
            // If we're close to the expanded text size, snap to it and use a scale of 1
            mScale = 1f;
        } else {
            // Else, we'll scale down from the expanded text size
            mScale = textSize / mExpandedTextSize;
        }
        // BEGIN MODIFICATION: Set maxLines variable
        maxLines = this.maxLines;
        // END MODIFICATION
    }
    if (availableWidth > 0) {
        updateDrawText = (mCurrentTextSize != newTextSize) || mBoundsChanged || updateDrawText;
        mCurrentTextSize = newTextSize;
        mBoundsChanged = false;
    }
    if (mTextToDraw == null || updateDrawText) {
        mTextPaint.setTextSize(mCurrentTextSize);
        mTextPaint.setTypeface(mCurrentTypeface);

        // BEGIN MODIFICATION: Text layout creation and text truncation
        StaticLayout layout = new StaticLayout(mText, mTextPaint, (int) availableWidth,
                Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
        CharSequence truncatedText;
        if (layout.getLineCount() > maxLines) {
            int lastLine = maxLines - 1;
            CharSequence textBefore = lastLine > 0 ? mText.subSequence(0, layout.getLineEnd(lastLine - 1)) : "";
            CharSequence lineText = mText.subSequence(layout.getLineStart(lastLine),
                    layout.getLineEnd(lastLine));
            // if last char in line is space, move it behind the ellipsis
            CharSequence lineEnd = "";
            if (lineText.charAt(lineText.length() - 1) == ' ') {
                lineEnd = lineText.subSequence(lineText.length() - 1, lineText.length());
                lineText = lineText.subSequence(0, lineText.length() - 1);
            }
            // insert ellipsis character
            lineText = TextUtils.concat(lineText, "\u2026", lineEnd);
            // if the text is too long, truncate it
            CharSequence truncatedLineText = TextUtils.ellipsize(lineText, mTextPaint, availableWidth,
                    TextUtils.TruncateAt.END);
            truncatedText = TextUtils.concat(textBefore, truncatedLineText);

        } else {
            truncatedText = mText;
        }
        if (!TextUtils.equals(truncatedText, mTextToDraw)) {
            mTextToDraw = truncatedText;
            mIsRtl = calculateIsRtl(mTextToDraw);
        }

        final Layout.Alignment alignment;

        // Don't rectify gravity for RTL languages, Layout.Alignment does it already.
        switch (mExpandedTextGravity & GravityCompat.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
        case Gravity.CENTER_HORIZONTAL:
            alignment = Layout.Alignment.ALIGN_CENTER;
            break;
        case Gravity.RIGHT:
        case Gravity.END:
            alignment = Layout.Alignment.ALIGN_OPPOSITE;
            break;
        case Gravity.LEFT:
        case Gravity.START:
        default:
            alignment = Layout.Alignment.ALIGN_NORMAL;
            break;
        }

        mTextLayout = new StaticLayout(mTextToDraw, mTextPaint, (int) availableWidth, alignment, 1, 0, false);
        // END MODIFICATION
    }
}

From source file:org.archive.crawler.extractor.ExtractorHTML.java

/**
 * Process metadata tags.//from   w  w  w. j  av a  2 s. c  o m
 * 
 * @param curi
 *            CrawlURI we're processing.
 * @param cs
 *            Sequence from underlying ReplayCharSequence. This is TRANSIENT
 *            data. Make a copy if you want the data to live outside of this
 *            extractors' lifetime.
 * @return True robots exclusion metatag.
 */
protected boolean processMeta(CrawlURI curi, CharSequence cs) {
    // System.out.println("I'm processMeta " + curi.toString() + "");
    Matcher attr = TextUtils.getMatcher(EACH_ATTRIBUTE_EXTRACTOR, cs);
    String name = null;
    String httpEquiv = null;
    String content = null;
    while (attr.find()) {
        int valueGroup = (attr.start(14) > -1) ? 14 : (attr.start(15) > -1) ? 15 : 16;
        CharSequence value = cs.subSequence(attr.start(valueGroup), attr.end(valueGroup));
        value = TextUtils.unescapeHtml(value);
        if (attr.group(1).equalsIgnoreCase("name")) {
            name = value.toString();
        } else if (attr.group(1).equalsIgnoreCase("http-equiv")) {
            httpEquiv = value.toString();
        } else if (attr.group(1).equalsIgnoreCase("content")) {
            content = value.toString();
        }
        // TODO: handle other stuff
    }
    TextUtils.recycleMatcher(attr);

    // Look for the 'robots' meta-tag
    if ("robots".equalsIgnoreCase(name) && content != null) {
        curi.putString(A_META_ROBOTS, content);
        RobotsHonoringPolicy policy = getSettingsHandler().getOrder().getRobotsHonoringPolicy();
        String contentLower = content.toLowerCase();
        if ((policy == null || (!policy.isType(curi, RobotsHonoringPolicy.IGNORE)
                && !policy.isType(curi, RobotsHonoringPolicy.CUSTOM)))
                && (contentLower.indexOf("nofollow") >= 0 || contentLower.indexOf("none") >= 0)) {
            // if 'nofollow' or 'none' is specified and the
            // honoring policy is not IGNORE or CUSTOM, end html extraction
            logger.fine("HTML extraction skipped due to robots meta-tag for: " + curi.toString());
            return true;
        }
    } else if ("refresh".equalsIgnoreCase(httpEquiv) && content != null) {
        int urlIndex = content.indexOf("=") + 1;
        if (urlIndex > 0) {
            String refreshUri = content.substring(urlIndex);
            try {
                curi.createAndAddLinkRelativeToBase(refreshUri, "meta", Link.REFER_HOP);
            } catch (URIException e) {
                if (getController() != null) {
                    getController().logUriError(e, curi.getUURI(), refreshUri);
                } else {
                    logger.info("Failed createAndAddLinkRelativeToBase " + curi + ", " + cs + ", " + refreshUri
                            + ": " + e);
                }
            }
        }
    }
    return false;
}

From source file:org.archive.modules.extractor.ExtractorHTML.java

/**
 * Process metadata tags.// w  w w .  j  a  v a 2 s  .  c  om
 * @param curi CrawlURI we're processing.
 * @param cs Sequence from underlying ReplayCharSequence. This
 * is TRANSIENT data. Make a copy if you want the data to live outside
 * of this extractors' lifetime.
 * @return True robots exclusion metatag.
 */
protected boolean processMeta(CrawlURI curi, CharSequence cs) {
    Matcher attr = TextUtils.getMatcher(eachAttributePattern, cs);
    String name = null;
    String httpEquiv = null;
    String content = null;
    while (attr.find()) {
        int valueGroup = (attr.start(14) > -1) ? 14 : (attr.start(15) > -1) ? 15 : 16;
        CharSequence value = cs.subSequence(attr.start(valueGroup), attr.end(valueGroup));
        value = TextUtils.unescapeHtml(value);
        if (attr.group(1).equalsIgnoreCase("name")) {
            name = value.toString();
        } else if (attr.group(1).equalsIgnoreCase("http-equiv")) {
            httpEquiv = value.toString();
        } else if (attr.group(1).equalsIgnoreCase("content")) {
            content = value.toString();
        }
        // TODO: handle other stuff
    }
    TextUtils.recycleMatcher(attr);

    // Look for the 'robots' meta-tag
    if ("robots".equalsIgnoreCase(name) && content != null) {
        curi.getData().put(A_META_ROBOTS, content);
        RobotsPolicy policy = metadata.getRobotsPolicy();
        String contentLower = content.toLowerCase();
        if (policy.obeyMetaRobotsNofollow()
                && (contentLower.indexOf("nofollow") >= 0 || contentLower.indexOf("none") >= 0)) {
            // if 'nofollow' or 'none' is specified and the
            // honoring policy is not IGNORE or CUSTOM, end html extraction
            logger.fine("HTML extraction skipped due to robots meta-tag for: " + curi.toString());
            return true;
        }
    } else if ("refresh".equalsIgnoreCase(httpEquiv) && content != null) {
        int urlIndex = content.indexOf("=") + 1;
        if (urlIndex > 0) {
            String refreshUri = content.substring(urlIndex);
            try {
                int max = getExtractorParameters().getMaxOutlinks();
                addRelativeToBase(curi, max, refreshUri, HTMLLinkContext.META, Hop.REFER);
            } catch (URIException e) {
                logUriError(e, curi.getUURI(), refreshUri);
            }
        }
    } else if (content != null) {
        //look for likely urls in 'content' attribute
        try {
            if (UriUtils.isVeryLikelyUri(content)) {
                int max = getExtractorParameters().getMaxOutlinks();
                addRelativeToBase(curi, max, content, HTMLLinkContext.META, Hop.SPECULATIVE);
            }
        } catch (URIException e) {
            logUriError(e, curi.getUURI(), content);
        }
    }
    return false;
}

From source file:com.ericsun.duom.Framework.Activity.BaseActivity.java

public void setPricePoint(final EditText editText) {
    editText.addTextChangedListener(new TextWatcher() {

        @Override//from   w  w w  .  j a va2s  .  c o m
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                    s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                    editText.setText(s);
                    editText.setSelection(s.length());
                }
            }
            if (s.toString().trim().substring(0).equals(".")) {
                s = "";
            }

            if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    editText.setText(s.subSequence(0, 1));
                    editText.setSelection(1);
                    return;
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            // TODO Auto-generated method stub
        }

    });

}

From source file:com.cyberway.issue.crawler.extractor.ExtractorHTML.java

/**
 * Run extractor./*w  w w . j  a va  2  s  .co  m*/
 * This method is package visible to ease testing.
 * @param curi CrawlURI we're processing.
 * @param cs Sequence from underlying ReplayCharSequence. This
 * is TRANSIENT data. Make a copy if you want the data to live outside
 * of this extractors' lifetime.
 */
void extract(CrawlURI curi, CharSequence cs) {
    Matcher tags = TextUtils.getMatcher(RELEVANT_TAG_EXTRACTOR, cs);
    while (tags.find()) {
        if (Thread.interrupted()) {
            break;
        }
        if (tags.start(8) > 0) {
            // comment match
            // for now do nothing
        } else if (tags.start(7) > 0) {
            // <meta> match
            int start = tags.start(5);
            int end = tags.end(5);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            if (processMeta(curi, cs.subSequence(start, end))) {

                // meta tag included NOFOLLOW; abort processing
                break;
            }
        } else if (tags.start(5) > 0) {
            // generic <whatever> match
            int start5 = tags.start(5);
            int end5 = tags.end(5);
            assert start5 >= 0 : "Start is: " + start5 + ", " + curi;
            assert end5 >= 0 : "End is :" + end5 + ", " + curi;
            int start6 = tags.start(6);
            int end6 = tags.end(6);
            assert start6 >= 0 : "Start is: " + start6 + ", " + curi;
            assert end6 >= 0 : "End is :" + end6 + ", " + curi;
            processGeneralTag(curi, cs.subSequence(start6, end6), cs.subSequence(start5, end5));

        } else if (tags.start(1) > 0) {
            // <script> match
            int start = tags.start(1);
            int end = tags.end(1);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(2) >= 0 : "Tags.end(2) illegal " + tags.end(2) + ", " + curi;
            processScript(curi, cs.subSequence(start, end), tags.end(2) - start);

        } else if (tags.start(3) > 0) {
            // <style... match
            int start = tags.start(3);
            int end = tags.end(3);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(4) >= 0 : "Tags.end(4) illegal " + tags.end(4) + ", " + curi;
            processStyle(curi, cs.subSequence(start, end), tags.end(4) - start);
        }
    }
    TextUtils.recycleMatcher(tags);
}

From source file:org.openqa.selendroid.server.model.AndroidNativeElement.java

protected void send(CharSequence string) {
    int currentIndex = 0;

    instrumentation.waitForIdleSync();//  www . j  av a2s  .  co m

    while (currentIndex < string.length()) {
        char currentCharacter = string.charAt(currentIndex);
        if (AndroidKeys.hasAndroidKeyEvent(currentCharacter)) {
            // The next character is special and must be sent individually
            instrumentation.sendKeyDownUpSync(AndroidKeys.keyCodeFor(currentCharacter));
            currentIndex++;
        } else {
            // There is at least one "normal" character, that is a character
            // represented by a plain Unicode character that can be sent
            // with
            // sendStringSync. So send as many such consecutive normal
            // characters
            // as possible in a single String.
            int nextSpecialKey = indexOfSpecialKey(string, currentIndex);
            instrumentation.sendStringSync(string.subSequence(currentIndex, nextSpecialKey).toString());
            currentIndex = nextSpecialKey;
        }
    }
}

From source file:org.cleverbus.common.Strings.java

/**
 * Replace all occurrences of one string replaceWith another string.
 *
 * @param s//w w  w . ja va2 s . c o m
 *            The string to process
 * @param searchFor
 *            The value to search for
 * @param replaceWith
 *            The value to searchFor replaceWith
 * @return The resulting string with searchFor replaced with replaceWith
 */
public static CharSequence replaceAll(CharSequence s, CharSequence searchFor, CharSequence replaceWith) {
    if (s == null) {
        return null;
    }

    // If searchFor is null or the empty string, then there is nothing to
    // replace, so returning s is the only option here.
    if ((searchFor == null) || EMPTY.equals(searchFor)) {
        return s;
    }

    // If replaceWith is null, then the searchFor should be replaced with
    // nothing, which can be seen as the empty string.
    if (replaceWith == null) {
        replaceWith = EMPTY;
    }

    String searchString = searchFor.toString();
    // Look for first occurrence of searchFor
    int matchIndex = search(s, searchString, 0);
    if (matchIndex == -1) {
        // No replace operation needs to happen
        return s;
    } else {
        // Allocate a AppendingStringBuffer that will hold one replacement
        // with a
        // little extra room.
        int size = s.length();
        final int replaceWithLength = replaceWith.length();
        final int searchForLength = searchFor.length();
        if (replaceWithLength > searchForLength) {
            size += (replaceWithLength - searchForLength);
        }
        final StringBuilder sb = new StringBuilder(size + 16);

        int pos = 0;
        do {
            // Append text up to the match`
            append(sb, s, pos, matchIndex);

            // Add replaceWith text
            sb.append(replaceWith);

            // Find next occurrence, if any
            pos = matchIndex + searchForLength;
            matchIndex = search(s, searchString, pos);
        } while (matchIndex != -1);

        // Add tail of s
        sb.append(s.subSequence(pos, s.length()));

        // Return processed buffer
        return sb;
    }
}

From source file:org.archive.crawler.extractor.ExtractorHTML.java

/**
 * Run extractor. This method is package visible to ease testing.
 * /*w w  w  . j  av a 2 s  . c  om*/
 * @param curi
 *            CrawlURI we're processing.
 * @param cs
 *            Sequence from underlying ReplayCharSequence. This is TRANSIENT
 *            data. Make a copy if you want the data to live outside of this
 *            extractors' lifetime.
 */
void extract(CrawlURI curi, CharSequence cs) {
    Matcher tags = TextUtils.getMatcher(RELEVANT_TAG_EXTRACTOR, cs);

    while (tags.find()) {
        if (Thread.interrupted()) {
            break;
        }
        if (tags.start(8) > 0) {
            // comment match
            // for now do nothing
        } else if (tags.start(7) > 0) {
            // <meta> match
            int start = tags.start(5);
            int end = tags.end(5);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            if (processMeta(curi, cs.subSequence(start, end))) {

                // meta tag included NOFOLLOW; abort processing
                break;
            }
        } else if (tags.start(5) > 0) {
            // generic <whatever> match
            int start5 = tags.start(5);
            int end5 = tags.end(5);
            assert start5 >= 0 : "Start is: " + start5 + ", " + curi;
            assert end5 >= 0 : "End is :" + end5 + ", " + curi;
            int start6 = tags.start(6);
            int end6 = tags.end(6);
            assert start6 >= 0 : "Start is: " + start6 + ", " + curi;
            assert end6 >= 0 : "End is :" + end6 + ", " + curi;
            processGeneralTag(curi, cs.subSequence(start6, end6), cs.subSequence(start5, end5));

        } else if (tags.start(1) > 0) {
            // <script> match
            int start = tags.start(1);
            int end = tags.end(1);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(2) >= 0 : "Tags.end(2) illegal " + tags.end(2) + ", " + curi;
            processScript(curi, cs.subSequence(start, end), tags.end(2) - start);

        } else if (tags.start(3) > 0) {
            // <style... match
            int start = tags.start(3);
            int end = tags.end(3);
            assert start >= 0 : "Start is: " + start + ", " + curi;
            assert end >= 0 : "End is :" + end + ", " + curi;
            assert tags.end(4) >= 0 : "Tags.end(4) illegal " + tags.end(4) + ", " + curi;
            processStyle(curi, cs.subSequence(start, end), tags.end(4) - start);
        }
    }
    TextUtils.recycleMatcher(tags);
}

From source file:com.intellij.lang.jsgraphql.ide.annotator.JSGraphQLAnnotator.java

private CharSequence getWhitespacePaddedGraphQL(PsiFile psiFile, CharSequence buffer) {
    // find the template expressions in the file
    Collection<JSStringTemplateExpression> stringTemplateExpressions = PsiTreeUtil
            .collectElementsOfType(psiFile, JSStringTemplateExpression.class);
    StringBuilder sb = new StringBuilder(0);
    Integer builderPos = null;/*from  w  w  w . ja  v  a 2s.c om*/
    for (JSStringTemplateExpression stringTemplateExpression : stringTemplateExpressions) {
        if (JSGraphQLLanguageInjectionUtil.isJSGraphQLLanguageInjectionTarget(stringTemplateExpression)) {
            final TextRange graphQLTextRange = JSGraphQLLanguageInjectionUtil
                    .getGraphQLTextRange(stringTemplateExpression);
            if (builderPos == null) {
                sb.setLength(buffer.length());
                builderPos = 0;
            }
            // write the JS as whitespace so it'll be ignored by the GraphQL tooling, while preserving line numbers and columns.
            TextRange templateTextRange = stringTemplateExpression.getTextRange();
            int graphQLStartOffset = templateTextRange.getStartOffset() + graphQLTextRange.getStartOffset();
            int graphQLEndOffset = templateTextRange.getStartOffset() + graphQLTextRange.getEndOffset();
            applyWhiteSpace(buffer, sb, builderPos, graphQLStartOffset);
            String graphQLText = buffer.subSequence(graphQLStartOffset, graphQLEndOffset /* end is exclusive*/)
                    .toString();
            sb.replace(graphQLStartOffset, graphQLEndOffset /* end is exclusive*/, graphQLText);
            builderPos = graphQLEndOffset /* start next whitespace padding after the graph ql */;
        }
    }

    // last whitespace segment
    if (builderPos != null && builderPos < buffer.length()) {
        applyWhiteSpace(buffer, sb, builderPos, buffer.length());
    }

    return sb;
}