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:org.adidac.io.EmbededOutputStream.java

/** Flush the internal buffer */
private void flushBuffer() throws IOException {
    String s = new String(buf, 0, count); // Uses system encoding.
    Matcher m = EMBED_PATTERN.matcher(s);
    String fileName;/*w w w  . ja  v a  2 s. c  o  m*/
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        fileName = m.group(1);
        String content = getContent(fileName);
        m.appendReplacement(sb, content);
    }
    m.appendTail(sb);
    out.write(sb.toString().getBytes());
    count = 0;
}

From source file:org.dd4t.core.resolvers.impl.DefaultLinkResolver.java

private String replacePlaceholders(String resolvedUrl, String placeholder, String replacementText) {
    StringBuffer sb = new StringBuffer();
    if (!StringUtils.isEmpty(replacementText)) {
        if (getEncodeUrl()) {
            try {
                replacementText = URLEncoder.encode(replacementText, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                LOG.warn("Not possible to encode string: " + replacementText, e);
                return "";
            }//from   ww w .j  av a 2s . c o  m
        }

        Pattern p = Pattern.compile(placeholder);
        Matcher m = p.matcher(resolvedUrl);

        while (m.find()) {
            m.appendReplacement(sb, replacementText);
        }
        m.appendTail(sb);
    }
    return sb.toString();
}

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

/**
 * Takes a string and replaces all the HTML symbols in it with their unescaped representation.
 * This should only affect substrings of the form &something; and not tags.
 * Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less
 * vague than that.// w  w w. j  av  a  2s. co m
 * @param html The HTML escaped text
 * @return The text with its HTML entities unescaped.
 */
private static String entsToTxt(String html) {
    // entitydefs defines nbsp as \xa0 instead of a standard space, so we
    // replace it first
    html = html.replace(" ", " ");
    Matcher htmlEntities = htmlEntitiesPattern.matcher(html);
    StringBuffer sb = new StringBuffer();
    while (htmlEntities.find()) {
        htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString());
    }
    htmlEntities.appendTail(sb);
    return sb.toString();
}

From source file:com.haulmont.cuba.core.sys.querymacro.TimeBetweenQueryMacroHandler.java

protected String replaceParamsInMacros(String macros, Map<String, Object> params) {
    Matcher matcher = QUERY_PARAM_PATTERN.matcher(macros);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String paramName = matcher.group(1);
        if (params.containsKey(paramName)) {
            matcher.appendReplacement(sb, params.get(paramName).toString());
            params.remove(paramName);//from  ww w .  java 2  s.c o m
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:dk.dma.msinm.common.time.TimeParser.java

/**
 * Parse the time description into its XML representation
 * @param time the time description to parse
 * @return the result/*from   ww  w  . j av a 2s  .co  m*/
 */
protected String parse(String time) throws TimeException {
    String monthMatch = "(" + Arrays.asList(months).stream().collect(Collectors.joining("|")) + ")";
    String seasonMatch = "(" + Arrays.asList(seasons).stream().collect(Collectors.joining("|")) + ")";
    String dayMatch = "(\\\\d{1,2})";
    String yearMatch = "(\\\\d{4})";
    String hourMatch = "(\\\\d{4})";
    String weekMatch = "(\\\\d{1,2})";

    BufferedReader reader = new BufferedReader(new StringReader(time));
    String line;
    StringBuilder result = new StringBuilder();
    try {
        while ((line = reader.readLine()) != null) {
            line = line.trim().toLowerCase();

            // Replace according to replace rules
            for (String key : rewriteRules.keySet()) {
                String value = rewriteRules.get(key);

                String from = key;
                from = from.replaceAll("\\$month", monthMatch);
                from = from.replaceAll("\\$season", seasonMatch);
                from = from.replaceAll("\\$date", dayMatch);
                from = from.replaceAll("\\$year", yearMatch);
                from = from.replaceAll("\\$hour", hourMatch);
                from = from.replaceAll("\\$week", weekMatch);

                Matcher m = Pattern.compile(from).matcher(line);
                StringBuffer sb = new StringBuffer();
                while (m.find()) {
                    String text = m.group();
                    m.appendReplacement(sb, value);
                }
                m.appendTail(sb);
                line = sb.toString();
            }
            result.append(line + "\n");
        }
    } catch (Exception e) {
        throw new TimeException("Failed converting time description into XML", e);
    }
    return "<time-result>" + result.toString() + "</time-result>";
}

From source file:com.haulmont.cuba.core.sys.querymacro.TimeBetweenQueryMacroHandler.java

@Override
public String replaceQueryParams(String queryString, Map<String, Object> params) {
    Matcher matcher = MACRO_PATTERN.matcher(queryString);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String macros = matcher.group(0);
        macros = replaceParamsInMacros(macros, params);
        matcher.appendReplacement(sb, macros);
    }//from w w w.  j  a va  2s.c o  m
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:com.googlecode.osde.internal.builders.GadgetBuilder.java

private void compileGadgetSpec(IFile source, IFile target, IProject project, IProgressMonitor monitor)
        throws CoreException, ParserException, UnsupportedEncodingException {
    Parser<Module> parser = ParserFactory.gadgetSpecParser();

    InputStream fileContent = source.getContents();
    Module module;/*  www  .ja  v a  2 s .  c o m*/
    try {
        module = parser.parse(fileContent);
    } finally {
        IOUtils.closeQuietly(fileContent);
    }

    List<Content> contents = module.getContent();
    Random rnd = new Random();
    for (Content content : contents) {
        if (ViewType.html.toString().equals(content.getType())) {
            String value = content.getValue();
            Pattern pattern = Pattern.compile("http://localhost:[0-9]+/" + project.getName()
                    + "/[-_.!~*\\'()a-zA-Z0-9;\\/?:\\@&=+\\$,%#]+\\.js");
            Matcher matcher = pattern.matcher(value);
            StringBuffer sb = new StringBuffer();
            while (matcher.find()) {
                matcher.appendReplacement(sb,
                        value.substring(matcher.start(), matcher.end()) + "?rnd=" + Math.abs(rnd.nextInt()));
            }
            matcher.appendTail(sb);
            content.setValue(sb.toString());
        }
    }
    String serialized = GadgetXmlSerializer.serialize(module);
    ByteArrayInputStream content = new ByteArrayInputStream(serialized.getBytes("UTF-8"));
    target.create(content, IResource.DERIVED | IResource.FORCE, monitor);
}

From source file:com.salas.bb.utils.StringUtils.java

/**
 * Complete recoding of all HTML entities into Unicode symbols.
 *
 * @param str string./*from  w ww .  j  a  va2 s .c o m*/
 *
 * @return result.
 */
public static String unescape(String str) {
    if (isEmpty(str))
        return str;

    Pattern p = Pattern.compile("&(([^#;\\s]{3,6})|#([0-9]{1,4})|#x([0-9a-fA-F]{1,4}));");
    Matcher m = p.matcher(str);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        Character c;

        String strEntity = m.group(2);
        String decEntity = m.group(3);
        String hexEntity = m.group(4);
        if (strEntity != null) {
            // String entity
            c = ENTITIES.get(strEntity);
        } else {
            c = decEntity != null ? (char) Integer.parseInt(decEntity) : (char) Integer.parseInt(hexEntity, 16);
        }

        m.appendReplacement(sb, c == null ? m.group() : c.toString());
    }
    m.appendTail(sb);

    return sb.toString();
}

From source file:adminServlets.AddProductServlet.java

private void uploadImage(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;//from  ww  w  . ja va2 s  .co  m
    try {

        out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paramaters.put(name, value);

            } else // processUploadedFile(item);
            {
                if (item.getSize() != 0) {
                    String itemName = item.getName();
                    Random generator = new Random();
                    int r = Math.abs(generator.nextInt());

                    String reg = "[.*]";
                    String replacingtext = "";

                    Pattern pattern = Pattern.compile(reg);
                    Matcher matcher = pattern.matcher(itemName);
                    StringBuffer buffer = new StringBuffer();

                    while (matcher.find()) {
                        matcher.appendReplacement(buffer, replacingtext);
                    }
                    int IndexOf = itemName.indexOf(".");
                    String domainName = itemName.substring(IndexOf);

                    String finalimage = buffer.toString() + "_" + r + domainName;

                    String path = "assets\\img\\bouques\\" + finalimage;
                    imgPaths.add(path);
                    File savedFile = new File(getServletContext().getRealPath("/") + path);

                    try {
                        item.write(savedFile);
                    } catch (Exception ex) {
                        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (IOException | FileUploadException ex) {
        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }

}

From source file:com.vmware.o11n.plugin.powershell.model.generate.ScriptActionGenerator.java

private String extractParameters(String script, ScriptModuleBuilder builder) {

    // first escape the PS script
    script = script.replace("'", "\\'");

    //Then look up for {#paramname#} and extract them
    Pattern pattern = Pattern.compile("\\{#([\\w]*)#\\}");
    Matcher matcher = pattern.matcher(script);

    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String inputName = matcher.group(1);
        // create input param
        builder.addParameter(inputName, "String");
        matcher.appendReplacement(sb, Matcher.quoteReplacement("' + " + inputName + " + '"));
    }/*w  w  w . j a va 2  s.  c  o m*/
    matcher.appendTail(sb);
    return sb.toString();
}