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:org.infoscoop.request.filter.ProxyHtmlUtil.java

private static Collection getReplacedHeaders(String url, Map<String, List<String>> responseHeaders) {
    int contextRoot = url.indexOf("://", 1);
    contextRoot = url.indexOf("/", contextRoot + 3);

    String contextUrl = (contextRoot > 0) ? url.substring(0, contextRoot) : url + "/";
    String[] replacement = { "$1" + contextUrl + "$2" };

    Collection headers = new ArrayList();
    for (Map.Entry<String, List<String>> header : responseHeaders.entrySet()) {

        String name = header.getKey();

        int idx = contains(name, REPLACE_HEADER);
        if (idx < 0)
            continue;
        for (String value : header.getValue()) {
            StringBuffer newValue = null;
            Matcher m = REPLACE_HEADER_PATTERN[idx].matcher(value);
            while (m.find()) {
                if (newValue == null)
                    newValue = new StringBuffer();

                m.appendReplacement(newValue, replacement[idx]);
            }//from  w ww. j av  a  2 s  .c o m

            if (newValue != null) {
                m.appendTail(newValue);
                log.info("Replace response header [" + name + " = " + newValue + "]");

                headers.add(new Header(name, newValue.toString()));
            }
        }
    }

    return headers;
}

From source file:com.age.core.orm.hibernate.HibernateDao.java

private static String removeOrders(String hql) {
    Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(hql);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, "");
    }//from  w  w w . ja  v  a  2 s.  c o m
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.csc.fi.ioapi.utils.LDHelper.java

public static String expandSparqlQuery(String query, Map<String, String> prefix_map) {

    for (Map.Entry<String, String> namespaces : prefix_map.entrySet()) {
        StringBuffer sb = new StringBuffer();
        /* Find curies starting with whitespace */
        String prefiz = " " + namespaces.getKey().concat(":");
        String REGEX = prefiz + "\\w*\\b";
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(query);

        while (m.find()) {
            StringBuffer replacement = new StringBuffer();
            replacement.append(" <").append(m.group().replace(prefiz, namespaces.getValue())).append(">");
            m.appendReplacement(sb, replacement.toString());
        }/*from   ww  w. j  a v  a 2 s . com*/

        m.appendTail(sb);
        query = sb.toString();

    }

    return query;
}

From source file:org.openhab.binding.ACDBCommon.db.DBManager.java

/**
 * execute insert /*w  w w.  j a v a2s  .  c  om*/
 *
 * @param insertSql
 * @param sqlParam
 * @throws Exception
 */
private static void insert(ServerInfo server, String insertSql, HashMap<String, String> sqlParam)
        throws Exception {
    Pattern sqlPattern = Pattern.compile("(\\?)");
    Matcher matcher = sqlPattern.matcher(insertSql);
    StringBuffer newSql = new StringBuffer();

    if (matcher.find()) {
        matcher.appendReplacement(newSql, sqlParam.get("value"));
    }

    if (matcher.find()) {
        matcher.appendReplacement(newSql, "'" + sqlParam.get("time") + "'");
    }
    matcher.appendTail(newSql);
    logger.debug("### sql:{}", newSql);

    try (PreparedStatement stmt = server.getConnection().prepareStatement(newSql.toString())) {
        stmt.executeUpdate();
    }
}

From source file:org.openhab.binding.ACDBCommon.db.DBManager.java

/**
 * execute update//www  .  j a  v  a2 s.c  o  m
 *
 * @param updateSql
 * @param sqlParam
 * @throws Exception
 */
private static void update(ServerInfo server, String updateSql, HashMap<String, String> sqlParam)
        throws Exception {
    Pattern sqlPattern = Pattern.compile("(\\?)");

    // analyze SQL statement
    Matcher matcher = sqlPattern.matcher(updateSql);
    StringBuffer newSql = new StringBuffer();

    while (matcher.find()) {
        String columnName = matcher.group(0);
        if (StringUtils.isNotEmpty(columnName)) {
            matcher.appendReplacement(newSql, sqlParam.get("value"));
        }
    }
    matcher.appendTail(newSql);
    logger.debug("### sql:{}", newSql);

    try (PreparedStatement stmt = server.getConnection().prepareStatement(newSql.toString())) {
        stmt.executeUpdate();
    }
}

From source file:net.sf.jabref.external.RegExpFileSearch.java

/**
 * Takes a string that contains bracketed expression and expands each of these using getFieldAndFormat.
 * <p>/*from   w  ww . jav  a2s  . c  o m*/
 * Unknown Bracket expressions are silently dropped.
 *
 * @param bracketString
 * @param entry
 * @param database
 * @return
 */
public static String expandBrackets(String bracketString, BibEntry entry, BibDatabase database) {
    Matcher m = SQUARE_BRACKETS_PATTERN.matcher(bracketString);
    StringBuffer s = new StringBuffer();
    while (m.find()) {
        String replacement = getFieldAndFormat(m.group(), entry, database);
        m.appendReplacement(s, replacement);
    }
    m.appendTail(s);

    return s.toString();
}

From source file:eu.nerdz.api.impl.fastreverse.messages.FastReverseConversationHandler.java

/**
 * Replaces a composite tag./*from  www .j a  v  a2s .  c  om*/
 * @param regex A regex
 * @param message A message to be parsed
 * @param format A format for pretty formatting. Only 2 string fields.
 * @return A string in which all occurrences of regex have been substituted with the contents matched
 */
private static String replaceDouble(String regex, String message, String format) {

    Matcher matcher = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(message);
    StringBuffer result = new StringBuffer();

    while (matcher.find()) {
        matcher.appendReplacement(result,
                String.format(format, matcher.group(1), matcher.group(2)).replace("$", "\\$"));
    }

    matcher.appendTail(result);

    return result.toString();

}

From source file:net.sf.jabref.external.RegExpFileSearch.java

/**
 * The actual work-horse. Will find absolute filepaths starting from the
 * given directory using the given regular expression string for search.
 *//*w ww .  j av  a 2s  .  c o m*/
private static List<File> findFile(BibEntry entry, File directory, String file, String extensionRegExp) {

    List<File> res = new ArrayList<>();

    File actualDirectory;
    if (file.startsWith("/")) {
        actualDirectory = new File(".");
        file = file.substring(1);
    } else {
        actualDirectory = directory;
    }

    // Escape handling...
    Matcher m = ESCAPE_PATTERN.matcher(file);
    StringBuffer s = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(s, m.group(1) + '/' + m.group(2));
    }
    m.appendTail(s);
    file = s.toString();
    String[] fileParts = file.split("/");

    if (fileParts.length == 0) {
        return res;
    }

    for (int i = 0; i < (fileParts.length - 1); i++) {

        String dirToProcess = fileParts[i];
        dirToProcess = expandBrackets(dirToProcess, entry, null);

        if (dirToProcess.matches("^.:$")) { // Windows Drive Letter
            actualDirectory = new File(dirToProcess + '/');
            continue;
        }
        if (".".equals(dirToProcess)) { // Stay in current directory
            continue;
        }
        if ("..".equals(dirToProcess)) {
            actualDirectory = new File(actualDirectory.getParent());
            continue;
        }
        if ("*".equals(dirToProcess)) { // Do for all direct subdirs

            File[] subDirs = actualDirectory.listFiles();
            if (subDirs != null) {
                String restOfFileString = StringUtil.join(fileParts, "/", i + 1, fileParts.length);
                for (File subDir : subDirs) {
                    if (subDir.isDirectory()) {
                        res.addAll(findFile(entry, subDir, restOfFileString, extensionRegExp));
                    }
                }
            }
        }
        // Do for all direct and indirect subdirs
        if ("**".equals(dirToProcess)) {
            List<File> toDo = new LinkedList<>();
            toDo.add(actualDirectory);

            String restOfFileString = StringUtil.join(fileParts, "/", i + 1, fileParts.length);

            while (!toDo.isEmpty()) {

                // Get all subdirs of each of the elements found in toDo
                File[] subDirs = toDo.remove(0).listFiles();
                if (subDirs == null) {
                    continue;
                }

                toDo.addAll(Arrays.asList(subDirs));

                for (File subDir : subDirs) {
                    if (!subDir.isDirectory()) {
                        continue;
                    }
                    res.addAll(findFile(entry, subDir, restOfFileString, extensionRegExp));
                }
            }

        } // End process directory information
    }

    // Last step: check if the given file can be found in this directory
    String filePart = fileParts[fileParts.length - 1].replace("[extension]", EXT_MARKER);
    String filenameToLookFor = expandBrackets(filePart, entry, null).replaceAll(EXT_MARKER, extensionRegExp);
    final Pattern toMatch = Pattern.compile('^' + filenameToLookFor.replaceAll("\\\\\\\\", "\\\\") + '$',
            Pattern.CASE_INSENSITIVE);

    File[] matches = actualDirectory.listFiles((arg0, arg1) -> {
        return toMatch.matcher(arg1).matches();
    });
    if ((matches != null) && (matches.length > 0)) {
        Collections.addAll(res, matches);
    }
    return res;
}

From source file:com.igormaznitsa.mindmap.model.ModelUtils.java

@Nonnull
public static String unescapeMarkdownStr(@Nonnull final String text) {
    String unescaped = UNESCAPE_BR.matcher(text).replaceAll("\n"); //NOI18N
    final StringBuffer result = new StringBuffer(text.length());
    final Matcher escaped = MD_ESCAPED_PATTERN.matcher(unescaped);
    while (escaped.find()) {
        final String group = escaped.group(1);
        escaped.appendReplacement(result, Matcher.quoteReplacement(group.substring(1)));
    }//from ww w  .  j  a va  2s . c  om
    escaped.appendTail(result);
    return result.toString();
}

From source file:org.etudes.component.app.jforum.util.html.SafeHtml.java

/**
 * removes existing target attribute in the anchor tag and adds target="_blank"
 * //w ww .ja v a  2 s .c om
 * @param contents
 *        Post contest
 * 
 * @return Modified content with target="_blank" in anchor tags
 */
public static String addAnchorTarget(String contents) {
    if (contents == null) {
        return null;
    }

    StringBuffer sb = new StringBuffer();

    Pattern p = Pattern.compile("<(a)([^>]+)>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
    Matcher m = p.matcher(contents);

    while (m.find()) {
        if (m.groupCount() == 2) {
            String group1 = m.group(1);
            String group2 = m.group(2);
            String modGroup2 = group2.replaceAll("(target\\s*=\\s*[\"\'][^\"\']*[\"\']\\s*)?", "");

            String modString = "<" + group1 + " target=\"_blank\" " + modGroup2 + ">";

            m.appendReplacement(sb, Matcher.quoteReplacement(modString));
        }
    }

    m.appendTail(sb);

    return sb.toString();
}