Example usage for java.util.regex Matcher start

List of usage examples for java.util.regex Matcher start

Introduction

In this page you can find the example usage for java.util.regex Matcher start.

Prototype

public int start() 

Source Link

Document

Returns the start index of the previous match.

Usage

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

/**
 * Look for a session and if it's completed or not found try 
 *                            re-validate existing security token
 *//*from  w  w w . j av  a  2s  .  co  m*/
@Override
public void validate(HttpServletRequest req, String stoken) throws WsSrvException {
    Session session = activeSessions.get(stoken);

    if (!(session == null || session.isFinished()))
        // Everything fine
        return;

    getLogger(req).debug("Local session validation faied." + " Sending POST request to validate SAML session");

    // Revalidate session
    PostMethod post = new PostMethod(_login);

    try {
        String ars = createAuthnRequest(getServiceLocation(req), getRefererUrl(req));
        post.setParameter("SAMLRequest", ars);
    } catch (MarshallingException | SignatureException | IOException e) {
        //-- 63
        throw new WsSrvException(63, e);
    }

    HttpClient hc = (new HttpClientBuilder()).buildClient();
    post.setRequestHeader("Cookie",
            (String) req.getSession().getServletContext().getAttribute("scookie_name") + "=" + stoken);

    int result;
    try {
        result = hc.executeMethod(post);
    } catch (IOException e) {
        //-- 66
        throw new WsSrvException(66, e);
    }

    // Expecting 200 if cookie valid and 302 if not, rest are errors
    if (result == HttpStatus.SC_OK) {
        // Extract end process SAML response from form
        String rb;
        try {
            rb = new String(post.getResponseBody());
        } catch (IOException e) {
            //-- 67
            throw new WsSrvException(67, e);
        }

        Matcher m = SAML_RESP.matcher(rb);

        if (m.matches() && m.groupCount() == 1) {
            String gs = m.group(1);

            // Convert hex decoded javascript variable
            String msg = "";
            int start = 0;
            Matcher m1 = HP.matcher(gs);

            while (m1.find()) {
                String dc = m1.group(1);
                int i = Integer.decode("#" + dc);

                int st = m1.start();
                int ed = m1.end();

                msg += gs.substring(start, st) + (char) i;
                start = ed;
            }

            try {
                procAuthnResponse(req, msg, stoken);
            } catch (Exception e) {
                //-- 62
                throw new WsSrvException(62, e);
            }
        }
    } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
        //-- 64
        throw new WsSrvException(64, "Redirect received");
    } else {
        //-- 65
        throw new WsSrvException(65, "Unexpected http return code " + result);
    }
}

From source file:com.sinosoft.one.data.jade.statement.SimpleInterpreter.java

public void interpret(StatementRuntime runtime) {

    final List<Object> parametersAsList = new LinkedList<Object>();

    // ??  :name ??
    Matcher matcher = NAMED_PARAM_PATTERN.matcher(runtime.getSQL());
    if (!matcher.find()) {
        return;/*ww w .jav  a2s  . c  o  m*/
    }

    final StringBuilder builder = new StringBuilder();

    int index = 0;

    do {
        // ??????
        String name = matcher.group(1);
        if (NumberUtils.isDigits(name)) {
            name = matcher.group();//??
        }

        Object value = null;

        // ?  a.b.c ?? 
        int find = name.indexOf('.');
        if (find >= 0) {

            //   BeanWrapper ?
            Object bean = runtime.getParameters().get(name.substring(0, find));
            if (bean != null) {
                BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
                value = beanWrapper.getPropertyValue(name.substring(find + 1));
            }

        } else {
            // ?
            value = runtime.getParameters().get(name);
        }

        // ?
        builder.append(runtime.getSQL().substring(index, matcher.start()));

        if (value instanceof Collection<?>) {

            //  IN (...) ?
            builder.append('(');

            Collection<?> collection = (Collection<?>) value;

            if (collection.isEmpty()) {
                builder.append("NULL");
            } else {
                builder.append('?');
            }

            for (int i = 1; i < collection.size(); i++) {
                builder.append(", ?");
            }

            builder.append(')');

            // ??
            parametersAsList.addAll(collection);

        } else {
            // ?
            builder.append('?');

            // ??
            parametersAsList.add(value);
        }

        index = matcher.end();

    } while (matcher.find());

    // ?
    builder.append(runtime.getSQL().substring(index));
    runtime.setSQL(builder.toString());
    runtime.setArgs(parametersAsList.toArray());
}

From source file:com.gzj.tulip.jade.statement.SimpleInterpreter.java

@Override
public void interpret(StatementRuntime runtime) {

    final List<Object> parametersAsList = new LinkedList<Object>();

    // ??  :name ??
    Matcher matcher = NAMED_PARAM_PATTERN.matcher(runtime.getSQL());
    if (!matcher.find()) {
        return;//from   w  w  w . ja  va  2  s  .c  om
    }

    final StringBuilder builder = new StringBuilder();

    int index = 0;

    do {
        // ??????
        String name = matcher.group(1);
        if (NumberUtils.isDigits(name)) {
            name = matcher.group();//??
        }

        Object value = null;

        // ?  a.b.c ?? 
        int find = name.indexOf('.');
        if (find >= 0) {

            //   BeanWrapper ?
            Object bean = runtime.getParameters().get(name.substring(0, find));
            if (bean != null) {
                BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
                value = beanWrapper.getPropertyValue(name.substring(find + 1));
            }

        } else {
            // ?
            value = runtime.getParameters().get(name);
        }

        // ?
        builder.append(runtime.getSQL().substring(index, matcher.start()));

        if (value instanceof Collection<?>) {

            //  IN (...) ?
            builder.append('(');

            Collection<?> collection = (Collection<?>) value;

            if (collection.isEmpty()) {
                builder.append("NULL");
            } else {
                builder.append('?');
            }

            for (int i = 1; i < collection.size(); i++) {
                builder.append(", ?");
            }

            builder.append(')');

            // ??
            parametersAsList.addAll(collection);

        } else {
            // ?
            builder.append('?');

            // ??
            parametersAsList.add(value);
        }

        index = matcher.end();

    } while (matcher.find());

    // ?
    builder.append(runtime.getSQL().substring(index));
    runtime.setSQL(builder.toString());
    runtime.setArgs(parametersAsList.toArray());
}

From source file:com.juick.android.MessageMenu.java

protected void collectURLs(String source, MessageID mid) {
    if (urls == null)
        urls = new ArrayList<String>();
    ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(source, mid);
    for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) {
        urls.add(foundURL.url);/*from ww  w  .j a v a2  s  .c  om*/
    }
    int pos = 0;
    Matcher m = JuickMessagesAdapter.getCrossReferenceMsgPattern(mid).matcher(source);
    while (m.find(pos)) {
        urls.add(source.substring(m.start(), m.end()));
        pos = m.end();
    }
}

From source file:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java

/**
 * Method is responsible for finding the patterns and returned the found data List.
 * // w w  w . j  a va 2 s. c  o  m
 * @param value
 * @param patternStr
 * @param spanList
 * @return
 * @throws DCMAApplicationException {@link DCMAApplicationException} Check for all the input parameters and find the pattern.
 */
public static final List<DataCarrier> findPattern(final String value, final String patternStr,
        final List<Span> spanList) throws DCMAApplicationException {

    String errMsg = null;
    List<DataCarrier> dataCarrierList = null;
    if (EphesoftStringUtil.isNullOrEmpty(value)) {
        errMsg = "Invalid input character sequence.";
        LOGGER.info(errMsg);
    } else if (null == patternStr || TableExtractionConstants.EMPTY.equals(patternStr)) {
        errMsg = "Invalid input pattern sequence.";
        throw new DCMAApplicationException(errMsg);
    } else {
        // Compile and use regular expression
        final CharSequence inputStr = value;
        final Pattern pattern = Pattern.compile(patternStr);
        final Matcher matcher = pattern.matcher(inputStr);
        List<Coordinates> coordinatesList = new ArrayList<Coordinates>();
        while (matcher.find()) {

            // Get all groups for this match
            for (int i = 0; i <= matcher.groupCount(); i++) {
                final String groupStr = matcher.group(i);
                if (groupStr != null) {
                    final int startIndex = matcher.start();
                    final int endIndex = startIndex + groupStr.trim().length();
                    List<Span> matchedSpans = null;
                    matchedSpans = PatternMatcherUtil.getMatchedSpans(spanList, startIndex, endIndex);
                    String matchedString = PatternMatcherUtil.getMatchedSpansValue(matchedSpans);
                    LOGGER.debug("Matched String is ", matchedString);
                    if (!EphesoftStringUtil.isNullOrEmpty(matchedString)) {
                        final float confidence = (groupStr.length()
                                * CommonConstants.DEFAULT_MAXIMUM_CONFIDENCE) / matchedString.length();
                        coordinatesList.clear();
                        for (Span span : matchedSpans) {
                            coordinatesList.add(span.getCoordinates());
                        }
                        Coordinates matchedCoordinates = HocrUtil.getRectangleCoordinates(coordinatesList);
                        final DataCarrier dataCarrier = new DataCarrier(matchedSpans, confidence, matchedString,
                                matchedCoordinates);
                        if (dataCarrierList == null) {
                            dataCarrierList = new ArrayList<DataCarrier>();
                        }
                        dataCarrierList.add(dataCarrier);
                        LOGGER.info(groupStr);
                    }
                }
            }
        }
    }

    return dataCarrierList;
}

From source file:ca.uhn.hl7v2.testpanel.model.msg.Hl7V2MessageCollection.java

private synchronized void doSetSourceMessageXml(String theMessage) {
    int rangeStart = 0;
    int rangeEnd = 0;

    Pattern p = Pattern.compile("<([A-Za-z0-9_]+).*?>");
    Matcher m = p.matcher(theMessage);

    while (rangeStart < theMessage.length() && m.find(rangeStart)) {

        int startIndex = m.start();
        String tagName = m.group(1);

        Pattern endP = Pattern.compile("</" + tagName + "(\\s.*?)?>");
        Matcher endM = endP.matcher(theMessage);
        boolean foundEnd = endM.find(startIndex);

        if (foundEnd) {

            String fullMsg = theMessage.substring(startIndex, endM.end());
            Hl7V2MessageXml nextMsg = new Hl7V2MessageXml();
            nextMsg.setIndexWithinCollection(myMessages.size());
            nextMsg.setRuntimeProfile(myRuntimeProfile);
            nextMsg.setEncoding(Hl7V2EncodingTypeEnum.XML);
            try {
                nextMsg.setSourceMessage(fullMsg);
                myMessages.add(nextMsg);
            } catch (PropertyVetoException e) {
                UnknownMessage nextUnk = new UnknownMessage(fullMsg);
                myMessages.add(nextUnk);
            }//from   w w  w.  ja va  2s .c  o m

            rangeEnd = endM.end();

        } else {

            String fullMsg = theMessage.substring(startIndex);
            UnknownMessage nextUnk = new UnknownMessage(fullMsg);
            myMessages.add(nextUnk);
            rangeEnd = theMessage.length();

        }

        myMessageRanges.add(new Range(rangeStart, rangeEnd));
        rangeStart = rangeEnd;

    }

    // for (String nextString : msgs) {
    //
    // if (StringUtils.isNotBlank(nextString)) {
    //
    // nextString = "<?xml" + nextString;
    // Hl7V2MessageXml nextMsg = new Hl7V2MessageXml();
    // nextMsg.setIndexWithinCollection(myMessages.size());
    // nextMsg.setRuntimeProfile(myRuntimeProfile);
    // nextMsg.setEncoding(Hl7V2EncodingTypeEnum.XML);
    // try {
    // nextMsg.setSourceMessage(nextString);
    // myMessages.add(nextMsg);
    // } catch (PropertyVetoException e) {
    // UnknownMessage nextUnk = new UnknownMessage(nextString);
    // myMessages.add(nextUnk);
    // }
    //
    // }
    // }
}

From source file:it.cnr.icar.eric.server.query.QueryManagerImpl.java

/**
 * Replaces named parameters in an SQLQuery with ? while placing
 * corresponding positional paramValues in queryParams List.
 * //from w  ww  .j a  v  a 2  s .com
 * @param query
 *            the AdhocQuery to be executed
 * @param queryParamsMap
 *            the Map in which each entry is a query param name/value pair
 * @param positionalParamValues
 *            a List of param values for each positional parameter in the
 *            PrepareStatment for the query
 */
@SuppressWarnings({ "rawtypes", "static-access" })
private AdhocQueryType plugQueryParameters(AdhocQueryType query, Map queryParamsMap,
        List<String> positionalParamValues) throws JAXBException {
    AdhocQueryType newQuery = query;
    positionalParamValues.clear(); // Start with empty list

    // Get the queryString
    QueryExpressionType queryExp = query.getQueryExpression();
    @SuppressWarnings("unused")
    String queryLang = queryExp.getQueryLanguage();
    String queryStr = (String) queryExp.getContent().get(0);
    String newQueryStr = new String(queryStr);
    log.debug("queryStr=" + queryStr);

    // Now replace parameterNames in queryString with ?
    // and add corresponding paramValue to quereyParams List
    // If a paramName is used more than once in queryString then
    // add corresponding paramValue multiple times in appropriate
    // position in positionalParamValues list
    // This would be easier with JDBC 3.0 nameParameters but support
    // is optional in JDBC 3.0 drivers and therefore not reliable.
    Iterator iter = queryParamsMap.keySet().iterator();

    Map<Integer, String> paramIndexToValueMap = new TreeMap<Integer, String>();

    // Process each $paramName by replacing it with ? in queryStr
    // and placing its paramValue in corresponding index on
    // positionalParamValues
    while (iter.hasNext()) {
        String paramName = (String) iter.next();
        String paramValue = queryParamsMap.get(paramName).toString();

        // Pattern to match $paramName optionally surrounded by single
        // quotes. First OR clause matches the longer option -- with
        // surrounding single quotes. Second OR clause matches
        // isolated parameter name.
        //
        // Some parameter names are prefixes of others ($considerPort
        // and $considerPortType for example) and this complicates the
        // second part. Must ensure we match the name only if it is
        // not a prefix. The zero-width negative lookahead checks this
        // case and does not mess up the replacement. Similar
        // zero-width negative lookbehind at start avoids matching (for
        // example) '$binding.transportType%' since that case would
        // result in '?%' and a parameter the underlying SQL parser
        // won't find. NOTE: Not checking for all parameters "buried"
        // in SQL string literals.
        //
        // TODO: The currently-used parameter name characters are
        // [a-zA-Z0-9.]. This goes beyond both [a-zA-Z0-9] from
        // [ebRS], section 6.3.1.1 and [a-zA-Z0-9_$#] previously in
        // SQLParser.jj. Rule below and latest SQLParser.jj <VARIABLE>
        // production are at least consistent. Should '.' be removed
        // from parameter names in WS Profile? Should both '.' and '_'
        // be disallowed in all parameter names?

        // Use Utility method as following is not in JDK 1.4
        // String quotedParamName = Pattern.quote(paramName);
        String quotedParamName = it.cnr.icar.eric.common.Utility.getInstance().quote(paramName);
        String paramNamePattern = "('" + quotedParamName + "')|" + "((?<!')" + quotedParamName
                + "(?![a-zA-Z0-9._]))";
        Pattern p = Pattern.compile(paramNamePattern);
        Matcher m = p.matcher(queryStr);

        // Remember start index of each occurance of paramName
        boolean found = false;
        while (m.find()) {
            found = true;
            paramIndexToValueMap.put(new Integer(m.start()), paramValue);
        }

        // Replace substrings matching paramNamePattern with ? Must be
        // done using separate matcher and string to keep
        // paramIndexToValueMap sorted
        if (found) {
            newQueryStr = p.matcher(newQueryStr).replaceAll("?");
        }
    }

    if (paramIndexToValueMap.size() > 0) {
        positionalParamValues.addAll(paramIndexToValueMap.values());
    }

    // Now re-constitute as query
    queryExp.getContent().clear();
    queryExp.getContent().add(newQueryStr);

    return newQuery;
}

From source file:com.norconex.collector.http.url.impl.HtmlLinkExtractor.java

private void extractLinks(String content, Referer referrer, Set<Link> links) {

    Matcher matcher = tagPattern.matcher(content);
    while (matcher.find()) {
        String tagName = matcher.group(1);
        String restOfTag = matcher.group(2);
        String text = null;//  w w  w. j a v a2s. c om
        if (StringUtils.isBlank(restOfTag)) {
            continue;
        }
        if ("meta".equalsIgnoreCase(tagName)) {
            extractMetaRefresh(restOfTag, referrer, links);
            continue;
        }
        if ("a".equalsIgnoreCase(tagName)) {
            if (!ignoreNofollow && isNofollow(restOfTag)) {
                continue;
            }
            if (keepReferrerData) {
                Matcher textMatcher = A_TEXT_PATTERN.matcher(content);
                if (textMatcher.find(matcher.start())) {
                    text = textMatcher.group(1).trim();
                }
            }
        }
        String attribs = tagAttribs.getString(tagName);
        Pattern p = Pattern.compile("(^|\\s)(" + attribs + ")\\s*=\\s*([\"'])([^\\<\\>]+?)\\3", PATTERN_FLAGS);
        Matcher urlMatcher = p.matcher(restOfTag);
        while (urlMatcher.find()) {
            String attribName = urlMatcher.group(2);
            String matchedUrl = urlMatcher.group(PATTERN_URL_GROUP);
            if (StringUtils.isBlank(matchedUrl)) {
                continue;
            }
            String[] urls = null;
            if ("object".equalsIgnoreCase(tagName)) {
                urls = StringUtils.split(matchedUrl, ' ');
            } else if ("applet".equalsIgnoreCase(tagName)) {
                urls = StringUtils.split(matchedUrl, ", ");
            } else {
                urls = new String[] { matchedUrl };
            }

            for (String url : urls) {
                url = toAbsoluteURL(referrer, url);
                if (url == null) {
                    continue;
                }
                Link link = new Link(url);
                if (keepReferrerData) {
                    link.setReferrer(referrer.url);
                    link.setTag(tagName + "." + attribName);
                    link.setText(text);
                }
                links.add(link);
            }
        }
    }
}

From source file:com.juick.android.JuickMessagesAdapter.java

public static ParsedMessage formatMessageText(final Context ctx, final JuickMessage jmsg, boolean condensed) {
    if (jmsg.parsedText != null) {
        return (ParsedMessage) jmsg.parsedText; // was parsed before
    }/*from   w ww.jav a2  s  .c  o  m*/
    getColorTheme(ctx);
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    int spanOffset = 0;
    final boolean isMainMessage = jmsg.getRID() == 0;
    final boolean doCompactComment = !isMainMessage && compactComments;
    if (jmsg.continuationInformation != null) {
        ssb.append(jmsg.continuationInformation + "\n");
        ssb.setSpan(new StyleSpan(Typeface.ITALIC), spanOffset, ssb.length() - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    //
    // NAME
    //
    spanOffset = ssb.length();
    String name = '@' + jmsg.User.UName;
    int userNameStart = ssb.length();
    ssb.append(name);
    int userNameEnd = ssb.length();
    StyleSpan userNameBoldSpan;
    ForegroundColorSpan userNameColorSpan;
    ssb.setSpan(userNameBoldSpan = new StyleSpan(Typeface.BOLD), spanOffset, ssb.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.setSpan(
            userNameColorSpan = new ForegroundColorSpan(
                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME, 0xFFC8934E)),
            spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    ssb.append(' ');
    spanOffset = ssb.length();

    if (!condensed) {
        //
        // TAGS
        //
        String tags = jmsg.getTags();
        if (feedlyFonts)
            tags = tags.toUpperCase();
        ssb.append(tags + "\n");
        if (tags.length() > 0) {
            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TAGS, 0xFF0000CC)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (feedlyFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.dinWebPro), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (helvNueFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        spanOffset = ssb.length();
    }
    if (jmsg.translated) {
        //
        // 'translated'
        //
        ssb.append("translated: ");
        ssb.setSpan(
                new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    int bodyOffset = ssb.length();
    int messageNumberStart = -1, messageNumberEnd = -1;
    if (showNumbers(ctx) && !condensed) {
        //
        // numbers
        //
        if (isMainMessage) {
            messageNumberStart = ssb.length();
            ssb.append(jmsg.getDisplayMessageNo());
            messageNumberEnd = ssb.length();
        } else {
            ssb.append("/" + jmsg.getRID());
            if (jmsg.getReplyTo() != 0) {
                ssb.append("->" + jmsg.getReplyTo());
            }
        }
        ssb.append(" ");
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.MESSAGE_ID, 0xFFa0a5bd)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    //
    // MESSAGE BODY
    //
    String txt = Censor.getCensoredText(jmsg.Text);
    if (!condensed) {
        if (jmsg.Photo != null) {
            txt = jmsg.Photo + "\n" + txt;
        }
        if (jmsg.Video != null) {
            txt = jmsg.Video + "\n" + txt;
        }
    }
    ssb.append(txt);
    boolean ssbChanged = false; // allocation optimization
    // Highlight links http://example.com/
    ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(txt, jmsg.getMID());
    ArrayList<String> urls = new ArrayList<String>();
    for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) {
        setSSBSpan(ssb, new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + foundURL.start, spanOffset + foundURL.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        urls.add(foundURL.url);
        if (foundURL.title != null) {
            ssb.replace(spanOffset + foundURL.title.start - 1, spanOffset + foundURL.title.start, " ");
            ssb.replace(spanOffset + foundURL.title.end, spanOffset + foundURL.title.end + 1, " ");
            ssb.replace(spanOffset + foundURL.start - 1, spanOffset + foundURL.start, "(");
            ssb.replace(spanOffset + foundURL.end, spanOffset + foundURL.end + 1, ")");
            ssb.setSpan(new StyleSpan(Typeface.BOLD), spanOffset + foundURL.title.start,
                    spanOffset + foundURL.title.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        ssbChanged = true;
    }
    // bold italic underline
    if (jmsg.Text.indexOf("*") != -1) {
        setStyleSpans(ssb, spanOffset, Typeface.BOLD, "*");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("/") != 0) {
        setStyleSpans(ssb, spanOffset, Typeface.ITALIC, "/");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("_") != 0) {
        setStyleSpans(ssb, spanOffset, UnderlineSpan.class, "_");
        ssbChanged = true;
    }
    if (ssbChanged) {
        txt = ssb.subSequence(spanOffset, ssb.length()).toString(); // ssb was modified in between
    }

    // Highlight nick
    String accountName = XMPPService.getMyAccountName(jmsg.getMID(), ctx);
    if (accountName != null) {
        int scan = spanOffset;
        String nickScanArea = (ssb + " ").toUpperCase();
        while (true) {
            int myNick = nickScanArea.indexOf("@" + accountName.toUpperCase(), scan);
            if (myNick != -1) {
                if (!isNickPart(nickScanArea.charAt(myNick + accountName.length() + 1))) {
                    setSSBSpan(ssb,
                            new BackgroundColorSpan(
                                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME_ME, 0xFF938e00)),
                            myNick - 1, myNick + accountName.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                scan = myNick + 1;
            } else {
                break;
            }
        }
    }

    // Highlight messages #1234
    int pos = 0;
    Matcher m = getCrossReferenceMsgPattern(jmsg.getMID()).matcher(txt);
    while (m.find(pos)) {
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + m.start(), spanOffset + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        pos = m.end();
    }

    SpannableStringBuilder compactDt = null;
    if (!condensed) {

        // found messages count (search results)
        if (jmsg.myFoundCount != 0 || jmsg.hisFoundCount != 0) {
            ssb.append("\n");
            int where = ssb.length();
            if (jmsg.myFoundCount != 0) {
                ssb.append(ctx.getString(R.string.MyReplies_) + jmsg.myFoundCount + "  ");
            }
            if (jmsg.hisFoundCount != 0) {
                ssb.append(ctx.getString(R.string.UserReplies_) + jmsg.hisFoundCount);
            }
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                    where, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        int rightPartOffset = spanOffset = ssb.length();

        if (!doCompactComment) {
            //
            // TIME (bottom of message)
            //

            try {
                DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                if (date.endsWith("/76"))
                    date = date.substring(0, date.length() - 3); // special case for no year in datasource
                ssb.append("\n" + date + " ");
            } catch (Exception e) {
                ssb.append("\n[fmt err] ");
            }

            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            compactDt = new SpannableStringBuilder();
            try {
                if (true || jmsg.deltaTime != Long.MIN_VALUE) {
                    compactDt.append(com.juickadvanced.Utils.toRelaviteDate(jmsg.Timestamp.getTime(), russian));
                } else {
                    DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                    String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                    if (date.endsWith("/76"))
                        date = date.substring(0, date.length() - 3); // special case for no year in datasource
                    compactDt.append(date);
                }
            } catch (Exception e) {
                compactDt.append("\n[fmt err] ");
            }
            compactDt.setSpan(
                    new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), 0,
                    compactDt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        spanOffset = ssb.length();

        //
        // Number of REPLIES
        //
        if (jmsg.replies > 0) {
            String replies = Replies + jmsg.replies;
            ssb.append(" " + replies);
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.NUMBER_OF_COMMENTS, 0xFFC8934E)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new WrapTogetherSpan() {
            }, spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!doCompactComment) {
            // right align
            ssb.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), rightPartOffset, ssb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), bodyOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    LeadingMarginSpan.LeadingMarginSpan2 userpicSpan = null;
    if (showUserpics(ctx) && !condensed) {
        userpicSpan = new LeadingMarginSpan.LeadingMarginSpan2() {
            @Override
            public int getLeadingMarginLineCount() {
                if (_wrapUserpics) {
                    return 2;
                } else {
                    return 22222;
                }
            }

            @Override
            public int getLeadingMargin(boolean first) {
                if (first) {
                    return (int) (2 * getLineHeight(ctx, (double) textScale));
                } else {
                    return 0;
                }
            }

            @Override
            public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                    CharSequence text, int start, int end, boolean first, Layout layout) {
            }
        };
        ssb.setSpan(userpicSpan, 0, ssb.length(), 0);
    }
    ParsedMessage parsedMessage = new ParsedMessage(ssb, urls);
    parsedMessage.userpicSpan = userpicSpan;
    parsedMessage.userNameBoldSpan = userNameBoldSpan;
    parsedMessage.userNameColorSpan = userNameColorSpan;
    parsedMessage.userNameStart = userNameStart;
    parsedMessage.userNameEnd = userNameEnd;
    parsedMessage.messageNumberStart = messageNumberStart;
    parsedMessage.messageNumberEnd = messageNumberEnd;
    parsedMessage.compactDate = compactDt;
    return parsedMessage;
}

From source file:TimeSpan.java

/**
 * Creates a time span using the date string to specify the time units and
 * amounts.  Time units are specified using a single lower case letter of
 * the word for the time unit, e.g. {@code y} for year, {@code m} for month.
 *
 * @param timespan a string containing numbers each followed by a single
 *        character to denote the time unit
 *
 * @throws IllegalArgumentException if <ul> <li> any of the parameters are
 *         negative <li> if any of the time units are specified more than
 *         once</ul>//from   ww w  . j  a  va  2  s .c o m
 */
public TimeSpan(String timespan) {

    Matcher matcher = TIME_SPAN_PATTERN.matcher(timespan);

    // Keep track of which time units have been set so far using a bit flag
    // pattern.  Each of the 5 units is stored as a single bit in order of
    // length, with longest first.
    int unitBitFlags = 0;

    // Assign default values of 0 to all of the time ranges before hand,
    // then overwite those with what data the timespan string contains
    int y = 0;
    int m = 0;
    int w = 0;
    int d = 0;
    int h = 0;

    int prevEnd = 0;
    while (matcher.find()) {
        // check that the next time unit has a proper format by ensuring
        // that all the patterns occur with no character gaps, e.g. 30d is
        // valid but 30dd will cause an error from the extra 'd'.
        if (matcher.start() != prevEnd) {
            throw new IllegalArgumentException("invalid time unit format: " + timespan);
        }
        prevEnd = matcher.end();
        String lengthStr = timespan.substring(matcher.start(), matcher.end() - 1);
        int length = Integer.parseInt(lengthStr);
        checkDuration(length);
        char timeUnit = timespan.charAt(matcher.end() - 1);

        // Update the appropriate time based on the unit
        switch (timeUnit) {
        case 'y':
            checkSetTwice(unitBitFlags, 0, "years");
            unitBitFlags |= (1 << 0);
            y = length;
            break;
        case 'm':
            checkSetTwice(unitBitFlags, 1, "months");
            unitBitFlags |= (1 << 1);
            m = length;
            break;
        case 'w':
            checkSetTwice(unitBitFlags, 2, "weeks");
            unitBitFlags |= (1 << 2);
            w = length;
            break;
        case 'd':
            checkSetTwice(unitBitFlags, 3, "days");
            unitBitFlags |= (1 << 3);
            d = length;
            break;
        case 'h':
            checkSetTwice(unitBitFlags, 4, "hours");
            unitBitFlags |= (1 << 4);
            h = length;
            break;
        default:
            throw new IllegalArgumentException("Unknown time unit: " + timeUnit);
        }
    }

    // update the final variables;
    years = y;
    months = m;
    weeks = w;
    days = d;
    hours = h;
}