Example usage for java.util.regex Matcher appendReplacement

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

Introduction

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

Prototype

public Matcher appendReplacement(StringBuilder sb, String replacement) 

Source Link

Document

Implements a non-terminal append-and-replace step.

Usage

From source file:net.sf.jasperreports.engine.export.FlashPrintElement.java

/**
 * Resolves hyperlink placeholders to URLs in a Flash variable.
 * //from   w  ww .ja  va 2  s .  c  o m
 * @param text the text in which hyperlink placeholders are to be replaced
 * @param element the print element where hyperlink parameters will be looked for
 * @param linkProducer the hyperlink producer which transforms hyperlink
 * objects to String URLs
 * @return the text with hyperlink placeholders replaced by URLs
 * @see #makeLinkPlaceholder(String)
 */
public static String resolveLinks(String text, JRGenericPrintElement element, JRHyperlinkProducer linkProducer,
        boolean prepareForSerialization) {
    Matcher matcher = LINK_PATTERN.matcher(text);
    StringBuffer xml = new StringBuffer();
    List<HyperlinkData> hyperlinksData = new ArrayList<HyperlinkData>();

    while (matcher.find()) {
        String paramName = matcher.group(LINK_PARAM_NAME_GROUP);
        JRPrintHyperlink hyperlink = (JRPrintHyperlink) element.getParameterValue(paramName);

        String replacement;
        if (hyperlink == null) {
            if (log.isWarnEnabled()) {
                log.warn("Hyperlink parameter " + paramName + " not found in element");
            }

            replacement = null;
        } else {
            replacement = linkProducer.getHyperlink(hyperlink);
            if (prepareForSerialization) {
                String id = String.valueOf(hyperlink.hashCode() & 0x7FFFFFFF);

                HyperlinkData hyperlinkData = new HyperlinkData();
                hyperlinkData.setId(id);
                hyperlinkData.setHref(replacement);
                hyperlinkData.setHyperlink(hyperlink);
                hyperlinkData.setSelector("._jrHyperLink." + hyperlink.getLinkType());
                replacement = "jrhl-" + id + ";" + hyperlink.getLinkType();

                hyperlinksData.add(hyperlinkData);
            }
        }

        if (replacement == null) {
            replacement = "";
        } else {
            try {
                if (!prepareForSerialization) {
                    replacement = URLEncoder.encode(replacement, "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
                throw new JRRuntimeException(e);
            }
        }

        matcher.appendReplacement(xml, replacement);
    }
    matcher.appendTail(xml);

    if (hyperlinksData.size() > 0) {
        element.setParameterValue("hyperlinksData", hyperlinksData);
    }

    return xml.toString();

}

From source file:org.b3log.symphony.service.ShortLinkQueryService.java

/**
 * Processes article short link (article id).
 *
 * @param content the specified content/*from   w w  w.  j  a  v  a  2 s  .co  m*/
 * @return processed content
 */
public String linkArticle(final String content) {
    final Matcher matcher = ID_PATTERN.matcher(content);
    final StringBuffer contentBuilder = new StringBuffer();

    try {
        while (matcher.find()) {
            final String linkId = StringUtils.substringBetween(matcher.group(), "[", "]");

            final Query query = new Query().addProjection(Article.ARTICLE_TITLE, String.class)
                    .setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, linkId));
            final JSONArray results = articleRepository.get(query).optJSONArray(Keys.RESULTS);
            if (0 == results.length()) {
                continue;
            }

            final JSONObject linkArticle = results.optJSONObject(0);

            final String linkTitle = linkArticle.optString(Article.ARTICLE_TITLE);
            final String link = " [" + linkTitle + "](" + Latkes.getServePath() + "/article/" + linkId + ") ";

            matcher.appendReplacement(contentBuilder, link);
        }
        matcher.appendTail(contentBuilder);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Generates article link error", e);
    }

    return contentBuilder.toString();
}

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  ww.j a v a2s  .c  om
        }

        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.encuestame.core.util.HTMLInputFilter.java

protected String validateEntities(String s) {
    // validate entities throughout the string
    Pattern pattern = Pattern.compile("&([^&;]*)(?=(;|&|$))");
    Matcher matcher = pattern.matcher(s);
    if (matcher.find()) {
        String one = matcher.group(1); // ([^&;]*)
        String two = matcher.group(2); // (?=(;|&|$))
        s = checkEntity(one, two);//from  ww  w. j  a  v a  2s .  c  om
    }

    // validate quotes outside of tags
    pattern = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);
    matcher = pattern.matcher(s);
    StringBuffer buf = new StringBuffer();
    if (matcher.find()) {
        String one = matcher.group(1); // (>|^)
        String two = matcher.group(2); // ([^<]+?)
        String three = matcher.group(3); // (<|$)
        matcher.appendReplacement(buf, one + two.replaceAll("\"", "&quot;") + three);
    }
    matcher.appendTail(buf);

    return s;
}

From source file:com.confighub.core.utils.FileUtils.java

private static String previewFile(final Context context, String fileContent, Map<String, Property> resolved,
        MultivaluedMap<String, String> passwords, Set<Long> breadcrumbs) {
    Collection<String> keyStrings = FileUtils.getKeys(fileContent);

    String patternString = "(?i)\\$\\{\\s*\\b(" + StringUtils.join(keyStrings, "|") + ")\\b\\s*}";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(fileContent);

    StringBuffer sb = new StringBuffer();

    while (matcher.find()) {
        String key = matcher.group(1);
        Property property = resolved.get(key);

        // replace each key specification with the property value
        String value = "";

        if (null != property) {
            if (null != property.getAbsoluteFilePath() && PropertyKey.ValueDataType.FileEmbed
                    .equals(property.getPropertyKey().getValueDataType())) {
                if (breadcrumbs.contains(property.getAbsoluteFilePath().getId())) {
                    JsonObject json = property.toJson();
                    json.addProperty("key", key);
                    throw new ConfigException(Error.Code.FILE_CIRCULAR_REFERENCE, json);
                }//  www.  j a v a  2 s . c  o  m

                breadcrumbs.add(property.getAbsoluteFilePath().getId());

                RepoFile injectFile = context.resolveFullContextFilePath(property.getAbsoluteFilePath());
                if (null == injectFile)
                    value = "[ ERROR: No file resolved ]";
                else
                    value = previewFile(context, injectFile.getContent(), resolved, passwords, breadcrumbs);
            } else {
                if (property.isEncrypted()) {
                    String spName = property.getPropertyKey().getSecurityProfile().getName();
                    if (null != passwords && passwords.containsKey(spName)) {
                        String password = passwords.get(spName).get(0);
                        if (!Utils.isBlank(password))
                            property.decryptValue(password);
                    }
                }
                value = setValue(property);
            }
        }

        matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
    }

    matcher.appendTail(sb);
    fileContent = sb.toString();

    // Remove all escapes \${...}
    fileContent = fileContent.replaceAll("\\\\\\$\\{", "\\$\\{");
    return fileContent;
}

From source file:com.g3net.tool.StringUtils.java

/**
 * src?regex????????(handler)/*  w w  w  .j  a va 2  s .com*/
 * ?????(regex?)?
 * 
 * @param src
 * @param regex
 *            ???? saa(\\d+)bb
 * @param handleGroupIndex
 *            regex?
 * @param hander
 * @return
 */
public static String replaceAll(String src, String regex, int handleGroupIndex, GroupHandler hander) {

    if (src == null || src.trim().length() == 0) {
        return "";
    }
    Matcher m = Pattern.compile(regex).matcher(src);

    StringBuffer sbuf = new StringBuffer();

    // perform the replacements:
    while (m.find()) {
        String value = m.group(handleGroupIndex);
        // int l = Integer.valueOf(value, 16).intValue();
        // char c=(char)(0x0ffff&l);
        // log.info(m.group(0));
        String handledStr = hander.handler(value);
        m.appendReplacement(sbuf, handledStr);

    }
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    return sbuf.toString();
    // return null;
}

From source file:com.hichinaschool.flashcards.libanki.importer.Anki2Importer.java

private String _mungeMedia(long mid, String fields) {
    String[] fs = Utils.splitFields(fields);

    for (int i = 0; i < fs.length; ++i) {
        for (Pattern p : Media.fMediaRegexps) {
            Matcher m = p.matcher(fs[i]);
            StringBuffer sb = new StringBuffer();
            while (m.find()) {
                String fname = m.group(2);
                BufferedInputStream srcData = _srcMediaData(fname);
                BufferedInputStream dstData = _dstMediaData(fname);
                if (srcData == null) {
                    // file was not in source, ignore
                    m.appendReplacement(sb, m.group(0));
                    continue;
                }/*from w  w  w.  j a  va2s .  c  o  m*/
                // if model-local file exists from a previous import, use that
                int extPos = fname.lastIndexOf(".");
                if (extPos <= 0) {
                    extPos = fname.length();
                }
                String lname = String.format(Locale.US, "%s_%d%s", fname.substring(0, extPos), mid,
                        fname.substring(extPos));
                if (mDst.getMedia().have(lname)) {
                    m.appendReplacement(sb, m.group(0).replace(fname, lname));
                    continue;
                } else if (dstData == null || compareMedia(srcData, dstData)) { // if missing or the same, pass unmodified
                    // need to copy?
                    if (dstData == null) {
                        _writeDstMedia(fname, srcData);
                    }
                    m.appendReplacement(sb, m.group(0));
                    continue;
                }
                // exists but does not match, so we need to dedupe
                _writeDstMedia(lname, srcData);
                m.appendReplacement(sb, m.group(0).replace(fname, lname));
            }
            m.appendTail(sb);
            fs[i] = sb.toString();
        }
    }
    return fields;
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static String stripWhitespace(String str) {
    if (str == null)
        return null;
    Matcher matcher = WHITESPACE.matcher(str);
    StringBuffer buffer = new StringBuffer();
    for (; matcher.find(); matcher.appendReplacement(buffer, ""))
        ;//from w w  w  . j av  a  2  s . c o  m
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:gtu._work.ui.RenameUI.java

private void usePatternNewNameBtnActionPerformed() {
    try {//from   ww w .j  av  a  2s.  co m
        String findFileRegex = Validate.notBlank(findFileRegexText.getText(), "??Regex");
        String renameRegex = Validate.notBlank(renameRegexText.getText(), "??");
        Pattern renameRegexPattern = Pattern.compile("\\#(\\w+)\\#");
        Matcher matcher2 = null;

        Pattern findFileRegexPattern = Pattern.compile(findFileRegex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = null;
        DefaultTableModel model = JTableUtil.createModel(false, "??", "??", "");

        int ind = 1;
        for (XFile f : fileList) {
            matcher = findFileRegexPattern.matcher(f.fileName);
            if (matcher.matches()) {
                StringBuffer sb = new StringBuffer();
                matcher2 = renameRegexPattern.matcher(renameRegex);
                while (matcher2.find()) {
                    String val = matcher2.group(1);
                    if (val.matches("\\d+L")) {
                        int index = Integer.parseInt(val.substring(0, val.length() - 1));
                        matcher2.appendReplacement(sb, DateFormatUtils
                                .format(Long.parseLong(matcher.group(index)), "yyyyMMdd_HHmmss"));
                    } else if (val.equalsIgnoreCase("date")) {
                        matcher2.appendReplacement(sb,
                                DateFormatUtils.format(f.file.lastModified(), "yyyyMMdd_HHmmss"));
                    } else if (val.equalsIgnoreCase("serial")) {
                        matcher2.appendReplacement(sb, String.valueOf(ind++));
                    } else if (StringUtils.isNumeric(val)) {
                        int index = Integer.parseInt(val);
                        matcher2.appendReplacement(sb, matcher.group(index));
                    }
                }
                matcher2.appendTail(sb);
                model.addRow(this.getXFile(f, sb.toString()));
            }
        }
        renameTable.setModel(model);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:org.nuclos.client.wizard.NuclosEntityWizardStaticModel.java

public List<String> getFieldsInNodeLabel() {
    List<String> lstFields = new ArrayList<String>();

    String sField = getNodeLabel();
    Pattern referencedEntityPattern = Pattern.compile("[$][{][\\w\\[\\]]+[}]");
    Matcher referencedEntityMatcher = referencedEntityPattern.matcher(sField);
    StringBuffer sb = new StringBuffer();

    while (referencedEntityMatcher.find()) {
        Object value = referencedEntityMatcher.group().substring(2,
                referencedEntityMatcher.group().length() - 1);

        String sName = value.toString();
        referencedEntityMatcher.appendReplacement(sb, sName);
    }/*ww w .  j a v  a2 s  .c om*/

    // complete the transfer to the StringBuffer
    referencedEntityMatcher.appendTail(sb);
    sField = sb.toString();

    String s = StringUtils.replace(StringUtils.replace(getNodeLabel(), "]", " "), "[", " ");
    if (s != null) {
        StringTokenizer st = new StringTokenizer(s, " ");
        while (st.hasMoreTokens()) {
            lstFields.add(st.nextToken());
        }
    }
    return lstFields;
}