Example usage for java.util.regex Matcher appendTail

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

Introduction

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

Prototype

public StringBuilder appendTail(StringBuilder sb) 

Source Link

Document

Implements a terminal append-and-replace step.

Usage

From source file:com.google.livingstories.server.dataservices.entities.BaseContentEntity.java

/**
 * Examines the content for anchor tags that look like they point to external pages
 *   (in general, any link that doesn't start with 'javascript:', and adds a
 *   target="_blank" attribute to them, if there isn't a target attribute already.
 * @param content Content to fix up./*from   w  ww .  ja v  a2  s .  c om*/
 * @return The modified content string, with links fixed to pop up new windows.
 */
private String fixLinks(String content) {
    Matcher matcher = EXTERNAL_LINK_PATTERN.matcher(content);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String link = matcher.group(0);
        if (!TARGET_ATTR_PATTERN.matcher(link).find()) {
            link = link.replace(">", DEFAULT_LINK_TARGET + ">");
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(link));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.apache.roller.weblogger.business.plugins.entry.BookmarkPlugin.java

private String matchBookmarks(String text, WeblogBookmarkFolder folder) {
    Iterator bookmarks = folder.getBookmarks().iterator();
    String workingText = text;/*from  ww  w . j  a v  a2s  .c  om*/
    while (bookmarks.hasNext()) {
        WeblogBookmark bookmark = (WeblogBookmark) bookmarks.next();
        String bkDescription = bookmark.getDescription();
        if (bkDescription == null)
            bkDescription = "";
        String bookmarkLink = "<a href=\"" + bookmark.getUrl() + "\" title=\"" + bkDescription + "\">"
                + bookmark.getName() + "</a>";
        try {
            // Replace all occurrences of bookmark name that don't occur within the bounds of an anchor tag
            // Notes:
            // - use reluctant quantifiers on the tags to avoid gobbling more than desired
            // - use non-capturing groups for boundaries to avoid replacing the boundary as well as the bookmark name.
            // - we depend on the numbering of the specific groups in this expression in the replacement code below.
            // TODO: should escape the bookmark name
            String regEx = "(<a(?:\\s.*?)??/>)|(<a(?:\\s.*?)??>)|(</a(?:\\s.*?)??>)|(?:\\b)("
                    + bookmark.getName() + ")(?:\\b)";
            Matcher m = Pattern.compile(regEx).matcher(workingText);
            StringBuffer textBuf = new StringBuffer(workingText.length());
            int inLink = 0;
            while (m.find()) {
                if (m.group(1) != null) {
                    // self-closed anchor tag <a  ... /> -- ignore
                } else if (m.group(2) != null) {
                    // matched opening anchor tag <a ...>
                    inLink++;
                } else if (m.group(3) != null) {
                    // closing anchor tag </a>, but ignore nonmatching ones
                    if (inLink > 0)
                        inLink--;
                } else if (m.group(4) != null) {
                    // matched the bookmark -- replace, but only if not within a link tag.
                    if (inLink == 0)
                        m.appendReplacement(textBuf, bookmarkLink);
                }
                // Any remaining case indicates a bug.  One could add an else with assertion here.  Conservatively don't substitute.
            }
            m.appendTail(textBuf);
            workingText = textBuf.toString();
        } catch (PatternSyntaxException e) {
            // Can happen since we don't escape pattern the bookmark name to protect pattern characters.
            mLogger.warn("Failed to substitute for bookmark [" + bookmark.getName()
                    + "] due to regular expression characters.");
        }
    }
    return workingText.toString();
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Percent-escape UTF-8 characters in local image filenames.
 * /*www  .  java2 s . c  om*/
 * @param string The string to search for image references and escape the filenames.
 * @return The string with the filenames of any local images percent-escaped as UTF-8.
 */
public String escapeImages(String string) {
    Matcher m = fMediaRegexps[1].matcher(string);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        if (fRemoteFilePattern.matcher(m.group(2)).find()) {
            m.appendReplacement(sb, m.group());
        } else {
            String tagBegin = m.group(1).substring(0, m.start(2));
            String fname = m.group(2);
            String tagEnd = m.group(1).substring(m.end(2));
            String tag = tagBegin + Uri.encode(fname) + tagEnd;
            m.appendReplacement(sb, tag);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

static String performStaticInclude(String includePatternString, String input) {
    String result = input;/*w  ww  . j  ava 2  s .c o  m*/
    boolean matchFound = true;

    Pattern staticIncludePattern = Pattern.compile(includePatternString);
    StringBuffer staticIncludeBuf;

    while (matchFound) {
        matchFound = false;
        staticIncludeBuf = new StringBuffer();
        Matcher staticIncludeMatcher = staticIncludePattern.matcher(result);
        while (staticIncludeMatcher.find()) {
            matchFound = true;
            String args = staticIncludeMatcher.group(1);
            try {
                if (!args.startsWith("/")) {
                    String servletPath = FacesContext.getCurrentInstance().getExternalContext()
                            .getRequestServletPath();
                    String workingDir = servletPath.substring(0, servletPath.lastIndexOf("/"));
                    args = workingDir + "/" + args;
                }
                String includeString = getInputAsString(new InputStreamReader(FacesContext.getCurrentInstance()
                        .getExternalContext().getResource(args).openConnection().getInputStream()));
                //Strip xml declarations from included files
                Pattern xmlDeclPattern = Pattern.compile(XML_DECL_PATTERN);
                Matcher xmlDeclMatcher = xmlDeclPattern.matcher(includeString);
                includeString = xmlDeclMatcher.replaceAll("");

                staticIncludeMatcher.appendReplacement(staticIncludeBuf, escapeBackreference(includeString));
            } catch (Exception e) {
                //an error occurred, just remove the include
                staticIncludeMatcher.appendReplacement(staticIncludeBuf, "");
                if (log.isErrorEnabled()) {
                    log.error("static include failed to include " + args, e);
                }
            }
        }
        staticIncludeMatcher.appendTail(staticIncludeBuf);
        result = staticIncludeBuf.toString();
    }
    return result;
}

From source file:org.etudes.mneme.impl.ImporteCollegeTextServiceImpl.java

public void importQuestions(String context, Pool pool, String text) throws AssessmentPermissionException {
    if ((text == null) || (text.length() == 0))
        return;/*from  w ww. j a  v a2s  . co m*/

    // replace any \r\n with just a \n
    text = text.replaceAll("\r\n", "\n");

    String title = "eCollege paste";
    Float points = new Float("1");

    if (pool == null) {
        pool = this.poolService.newPool(context);
        //read title from the first line ex: Unit 2: Week 2 - Quiz
        String findTitle = text.substring(0, text.indexOf("\n"));
        if (findTitle != null) {
            String[] titleParts = findTitle.split("[:-]");
            if (titleParts.length == 2 && titleParts[1] != null && titleParts[1].length() != 0)
                title = titleParts[1].trim();
            else if (titleParts.length > 2)
                title = findTitle.substring(findTitle.indexOf(titleParts[1]));
        }
        pool.setTitle(title);
        pool.setPointsEdit(points);

        // create assessment
        Assessment assmt = assessmentService.newAssessment(context);
        assmt.setType(AssessmentType.test);
        assmt.setTitle(title);

        Part part = assmt.getParts().addPart();

        Pattern p_groups = Pattern.compile("Collapse[\\s]*Question(.*?)[\\n]*[\\t]*row[\\t]*Move[\\s]*Question",
                Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);
        Matcher m = p_groups.matcher(text);

        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String workOn = m.group(0);
            String[] lines = workOn.split("[\\n]");
            processECollegeTextGroup(pool, part, lines);
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);

        // remaining last text
        if (sb != null && sb.length() != 0) {
            if (sb.indexOf("Collapse Question") != -1) {
                String workOn = sb.substring(sb.indexOf("Collapse Question"));
                String[] lines = workOn.split("[\\n]");
                processECollegeTextGroup(pool, part, lines);
            }
        }

        try {
            assmt.getGrading().setGradebookIntegration(Boolean.TRUE);

            if (assmt.getParts().getTotalPoints().floatValue() <= 0) {
                assmt.setNeedsPoints(Boolean.FALSE);
            }

            assessmentService.saveAssessment(assmt);
        } catch (AssessmentPolicyException ep) {

        }
        this.poolService.savePool(pool);

    }
}

From source file:org.codelibs.fess.helper.ViewHelper.java

public String getContentTitle(final Map<String, Object> document) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    String title = DocumentUtil.getValue(document, fessConfig.getIndexFieldTitle(), String.class);
    if (StringUtil.isBlank(title)) {
        title = DocumentUtil.getValue(document, fessConfig.getIndexFieldFilename(), String.class);
        if (StringUtil.isBlank(title)) {
            title = DocumentUtil.getValue(document, fessConfig.getIndexFieldUrl(), String.class);
        }/* w ww.  j a  v a2 s. c  o m*/
    }
    final int size = fessConfig.getResponseMaxTitleLengthAsInteger();
    if (size > -1) {
        title = StringUtils.abbreviate(title, size);
    }
    final String value = LaFunctions.h(title);
    if (!fessConfig.isResponseHighlightContentTitleEnabled()) {
        return value;
    }
    return getQuerySet().map(querySet -> {
        final Matcher matcher = Pattern
                .compile(querySet.stream().map(LaFunctions::h).map(Pattern::quote)
                        .collect(Collectors.joining("|")), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)
                .matcher(value);
        final StringBuffer buf = new StringBuffer(value.length() + 100);
        while (matcher.find()) {
            matcher.appendReplacement(buf, highlightTagPre + matcher.group(0) + highlightTagPost);
        }
        matcher.appendTail(buf);
        return buf.toString();
    }).orElse(value);
}

From source file:hudson.model.AbstractItem.java

/**
 * Writes {@code config.xml} to the specified output stream.
 * The user must have at least {@link #EXTENDED_READ}.
 * If he lacks {@link #CONFIGURE}, then any {@link Secret}s detected will be masked out.
 *//*w  w w  .  ja va 2 s  .c  om*/
@Restricted(NoExternalUse.class)
public void writeConfigDotXml(OutputStream os) throws IOException {
    checkPermission(EXTENDED_READ);
    XmlFile configFile = getConfigFile();
    if (hasPermission(CONFIGURE)) {
        IOUtils.copy(configFile.getFile(), os);
    } else {
        String encoding = configFile.sniffEncoding();
        String xml = FileUtils.readFileToString(configFile.getFile(), encoding);
        Matcher matcher = SECRET_PATTERN.matcher(xml);
        StringBuffer cleanXml = new StringBuffer();
        while (matcher.find()) {
            if (Secret.decrypt(matcher.group(1)) != null) {
                matcher.appendReplacement(cleanXml, ">********<");
            }
        }
        matcher.appendTail(cleanXml);
        org.apache.commons.io.IOUtils.write(cleanXml.toString(), os, encoding);
    }
}

From source file:com.zimbra.common.soap.SoapTestHarness.java

private String expandAllProps(String text) throws HarnessException {
    Matcher matcher = mPropPattern.matcher(text);
    StringBuffer sb = new StringBuffer();
    //System.out.println("("+text+")");
    while (matcher.find()) {
        String name = matcher.group(2);
        String replace = mProps.get(name);
        if (replace == null) {
            if (name.equals("TIME")) {
                replace = System.currentTimeMillis() + "";
            } else if (name.equals("COUNTER")) {
                replace = ++mCounter + "";
            }/*from  w  w  w.  jav a  2 s .  c  o m*/
        }

        if (replace != null) {
            matcher.appendReplacement(sb, replace);
        } else {
            throw new HarnessException("unknown property: " + matcher.group(1));
            //matcher.appendReplacement(sb, matcher.group(1));
        }
    }
    matcher.appendTail(sb);
    text = sb.toString();
    //System.out.println("("+text+")");
    return text;
}

From source file:org.apache.roller.weblogger.business.plugins.entry.SearchPluginBase.java

/**
 * Apply plugin to content of specified String.
 *
 * @param str String to which plugin should be applied.
 * @return Results of applying plugin to string.
 * @see org.apache.roller.weblogger.model.PagePlugin#render(String)
 *///from  w ww .  j  a v a 2  s  .co m
public String render(WeblogEntry entry, String str) {
    Pattern pattern = getPattern();
    Matcher m = pattern.matcher(str);
    StringBuffer result = new StringBuffer(str.length() + 128); // rough guess at a reasonable length
    Object[] args = new Object[] { "", "", null, null };
    while (m.find()) {
        // parse out the parts of the match
        String type = m.group(1);
        boolean feelinLucky = type.equals("!"); // are ya feelin lucky? are ya punk?
        String linkText = m.group(2);
        String searchText = m.group(3);
        if (searchText == null || searchText.length() == 0) {
            searchText = linkText;
        }

        // URL-encode the search text
        String encodedSearchText = encodeSearchText(searchText);

        // form the replacement string
        MessageFormat linkFormat = feelinLucky ? getLuckyLinkFormat() : getLinkFormat();
        StringBuffer replacement = new StringBuffer(128);
        args[2] = linkText;
        args[3] = encodedSearchText;
        linkFormat.format(args, replacement, new FieldPosition(0));

        // append replacement
        m.appendReplacement(result, replacement.toString());
    }
    m.appendTail(result);

    return result.toString();
}

From source file:net.duckling.ddl.web.controller.LynxDDocController.java

/**
 * uri???/*from www  .  j ava  2  s.c  o  m*/
 * @param html
 * @param cachePath
 * @param teamName
 * @param imagePathList
 * @return
 */
private String processImagePath(String html, String teamName, List<String> imagePathList,
        HttpServletRequest request) {
    String cachePath = getImageCachePath(request);
    String baseAddress = config.getProperty("duckling.baseAddress");
    String patternString = "src=\"((" + baseAddress + request.getContextPath() + "/|/)" + teamName
            + "/downloadResource/(\\d+))\"";

    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(html);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String imageUri = matcher.group(1);
        int rid;
        try {
            rid = Integer.valueOf(matcher.group(3));
        } catch (NumberFormatException e) {
            LOG.warn("parse rid error.{uri:" + imageUri + "} :" + e.getMessage());
            continue;
        }
        ;
        String path = createCacheImage(rid, cachePath);
        matcher.appendReplacement(sb, "src=\"" + path.replace("\\", "/") + "\"");
        imagePathList.add(path);
    }
    matcher.appendTail(sb);
    return sb.toString();
}