Example usage for java.util.regex Matcher quoteReplacement

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

Introduction

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

Prototype

public static String quoteReplacement(String s) 

Source Link

Document

Returns a literal replacement String for the specified String .

Usage

From source file:org.etudes.util.XrefHelper.java

/**
 * Replace any full URL references that include the server DNS, port, etc, with a root-relative one (i.e. starting with "/access" or "/library" or whatever)
 * /*w w  w  .  jav  a 2s . c o m*/
 * @param data
 *        the html data.
 * @return The shortened data.
 */
public static String shortenFullUrls(String data) {
    if (data == null)
        return data;

    Pattern p = getPattern();
    Matcher m = p.matcher(data);
    StringBuffer sb = new StringBuffer();

    // for the relative access check: matches ..\..\access\ etc with any number of leading "../"
    Pattern relAccessPattern = Pattern.compile("^(../)+(access/.*)");

    // to fix our messed up URLs with this pattern:
    // /access/content/private/meleteDocs/3349d4ca-38f3-4744-00c6-26715545e441/module_339214362/../../../../access/meleteDocs/content/private/meleteDocs/3349d4ca-38f3-4744-00c6-26715545e441/uploads/applelogohistory.jpg
    Pattern messUpFixPattern = Pattern.compile("^/access/content/.*(../)+(access/.*)");

    // process each "harvested" string (avoiding like strings that are not in src= or href= patterns)
    while (m.find()) {
        if (m.groupCount() == 3) {
            String ref = m.group(2);
            String terminator = m.group(3);
            String origRef = ref;

            // if this is an access to our own server, shorten it to root relative (i.e. starting with "/access")
            int pos = internallyHostedUrl(ref);
            if (pos != -1) {
                ref = ref.substring(pos);
                m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + ref + terminator));
            }

            // if this is a relative access URL, fix it
            else {
                Matcher relAccessMatcher = relAccessPattern.matcher(ref);
                if (relAccessMatcher.matches()) {
                    ref = "/" + relAccessMatcher.group(2);
                    m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + ref + terminator));
                }

                // fix a botched attempt a xref fixing that got tripped up with ../../../../access relative references
                else {
                    Matcher messUpFixer = messUpFixPattern.matcher(ref);
                    if (messUpFixer.matches()) {
                        ref = "/" + messUpFixer.group(2);
                        m.appendReplacement(sb,
                                Matcher.quoteReplacement(m.group(1) + "=\"" + ref + terminator));
                        M_log.warn("shortenFullUrls: fixing ref: " + origRef + " : to : " + ref);
                    }
                }
            }
        }
    }

    m.appendTail(sb);

    return sb.toString();
}

From source file:org.entando.edo.builder.TestBuilderNoPlugin.java

@Test
public void test_Controller_Jsp_Widget() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/sandbox/apsadmin/jsp/portal".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:fi.helsinki.cs.iot.hub.jsengine.DuktapeJavascriptEngineWrapper.java

private String jsonConfigToString(JSONArray json) {
    return json.toString().replaceAll("\"", Matcher.quoteReplacement("\\\""));
}

From source file:org.entando.edo.builder.TestBuilder.java

@Test
public void test_Controller_Jsp_Widget() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/plugins/jppet/apsadmin/jsp/portal".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:org.nuclos.common2.StringUtils.java

/**
 * Replaces all embedded parameters of the form <code>${...}</code>.
 * The replacement string is determined by calling a given transformer.
 * @param s the input string/*  w  ww . ja va 2  s.c o  m*/
 * @param t the transformer which maps a parameter to its replacement
 * @return the given string with all parameters replaced
 */
public static String replaceParameters(String s, Transformer<String, String> t) {
    if (s == null) {
        return null;
    }
    StringBuffer sb = new StringBuffer();
    Matcher m = PARAM_PATTERN.matcher(s);
    while (m.find()) {
        String resId = m.group(1);
        String repString = t.transform(resId);
        m.appendReplacement(sb, Matcher.quoteReplacement(repString));
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:org.alfresco.dropbox.service.polling.DropboxPollerImpl.java

private void updateNode(final NodeRef nodeRef, final Metadata metadata) {
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {
        public Object doWork() throws Exception {

            RetryingTransactionCallback<Object> txnWork = new RetryingTransactionCallback<Object>() {
                public Object execute() throws Exception {

                    if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_FOLDER)) {
                        try {
                            Metadata metadata = dropboxService.getMetadata(nodeRef);

                            // Get the list of the content returned.
                            List<Metadata> list = metadata.getContents();

                            for (Metadata child : list) {
                                String name = child.getPath()
                                        .replaceAll(Matcher.quoteReplacement(metadata.getPath() + "/"), "");

                                NodeRef childNodeRef = fileFolderService.searchSimple(nodeRef, name);

                                if (childNodeRef == null) {
                                    addNode(nodeRef, child, name);
                                } else {
                                    updateNode(childNodeRef, child);
                                }/*from ww  w  .j a  va 2  s  .com*/
                            }

                            metadata = dropboxService.getMetadata(nodeRef);

                            dropboxService.persistMetadata(metadata, nodeRef);
                        } catch (NotModifiedException nme) {

                        }

                    } else {
                        Serializable rev = nodeService.getProperty(nodeRef, DropboxConstants.Model.PROP_REV);

                        if (!metadata.getRev().equals(rev)) {
                            Metadata metadata = null;
                            try {
                                metadata = dropboxService.getFile(nodeRef);
                            } catch (ContentIOException cio) {
                                cio.printStackTrace();
                            }

                            if (metadata != null) {
                                dropboxService.persistMetadata(metadata, nodeRef);
                            } else {
                                throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                                        "Dropbox metadata maybe out of sync for " + nodeRef);
                            }
                        }

                    }
                    return null;
                }
            };

            transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false);

            return null;

        }
    }, AuthenticationUtil.getAdminUserName());
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

private void applyVariables(Map<String, String> variables) {
    Set<String> variableTokens = ActionUtils.getVariableNames(action);
    variableTokens.forEach((String originalName) -> {
        String[] parts = originalName.split("\\|");
        String var = parts[0];
        String replaceVar = Pattern.quote("${" + originalName + "}");
        String replace = variables.get(var) == null ? "" : variables.get(var);
        URL = URL.replaceAll(replaceVar, Matcher.quoteReplacement(replace));
        putFile = putFile.replaceAll(replaceVar, Matcher.quoteReplacement(replace));
    });/*from  w  w  w .ja va  2  s. c o m*/
    applyMultiVariablesToMap(variables, postVariables);
    applyMultiVariablesToMap(variables, getVariables);
    applyVariablesToMap(variables, requestHeaders);
}

From source file:org.entando.edo.builder.TestBuilderNoPlugin.java

@Test
public void test_Widget_Jsp() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/aps/jsp/widgets".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    String actualPath = ACTUAL_BASE_FOLDER + commonPath;

    File actualDir = new File(actualPath);
    Assert.assertTrue(actualDir.exists());

    List<File> actualFiles = this.searchFiles(actualDir, null);
    Assert.assertEquals(1, actualFiles.size());
    this.compareFiles(actualFiles);
}

From source file:com.googlecode.jmapper.util.GeneralUtility.java

/**
 * Replaces the variables present in the text and returns the result.<br>
 * @param text text to edit/*from   w ww .  ja  v  a 2  s  . c o  m*/
 * @param vars map with the string to replace as key and the respective value as value
 * @param prefix prefix
 * @return the text resultant
 */
private static String replace(String text, Map<String, String> vars, String prefix) {
    for (Entry<String, String> var : vars.entrySet())
        text = text.replaceAll(Pattern.quote(prefix + var.getKey()), Matcher.quoteReplacement(var.getValue()));

    return text;
}

From source file:edu.kit.dama.staging.adapters.DefaultStorageVirtualizationAdapter.java

/**
 * Create the destination folder for the ingest. This folder is located
 * withing the storage virtualization system. For this very basic adapter it
 * will be a folder with with a fixed scheme telling when the object was
 * uploaded by whom and which transfer id it had. The folder will be
 * generated as follows:/* w  w  w.  ja  va2s  . c o m*/
 *
 * <i>archiveURL</i>/<i>pathPattern</i>/SHA1(pTransferId) where
 * <i>pathPattern</i> allows the use or variables like $year, $month, $day
 * and $owner and pTransferId is the numeric id of the transfer.
 *
 * @param pTransferId The transfer id as it comes from the ingest
 * information entity.
 * @param pOwner The owner who ingested the object.
 *
 * @return An AbstractFile representing the destination for the final
 * ingest.
 *
 */
private AbstractFile createDestination(String pTransferId, IAuthorizationContext pContext) {
    if (pTransferId == null) {//transfer id is part of the destination, so it must not be null
        throw new IllegalArgumentException("Argument 'pTransferId' must not be 'null'");
    }

    String sUrl = archiveUrl.toString();
    if (pathPattern != null) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        String dynPath = pathPattern;
        dynPath = dynPath.replaceAll(Pattern.quote(YEAR_PATTERN), Integer.toString(year))
                .replaceAll(Pattern.quote(MONTH_PATTERN), Integer.toString(month))
                .replaceAll(Pattern.quote(DAY_PATTERN), Integer.toString(day));
        if (dynPath.contains(OWNER_PATTERN) || dynPath.contains(GROUP_PATTERN)) {//owner/group should be replaced by pattern definition
            if (pContext == null) {//uploader is 'null' but we need it for replacement
                throw new IllegalArgumentException(
                        "Argument 'pOwner' must not be 'null' if pattern contains element '" + OWNER_PATTERN
                                + "' or '" + GROUP_PATTERN + "'");
            } else {//everything is fine

                LOGGER.debug("Replacing owner/group pattern with values from context '{}'", pContext);
                dynPath = dynPath
                        .replaceAll(Pattern.quote(OWNER_PATTERN),
                                Matcher.quoteReplacement(pContext.getUserId().getStringRepresentation()))
                        .replaceAll(Pattern.quote(GROUP_PATTERN),
                                Matcher.quoteReplacement(pContext.getGroupId().getStringRepresentation()));
            }
        }
        LOGGER.debug("Appending pattern-based path '{}' to base destination '{}'",
                new Object[] { dynPath, sUrl });
        sUrl += "/" + dynPath;
    }

    //finally, create abstract file and return
    AbstractFile result;
    try {
        if (!sUrl.endsWith("/")) {
            sUrl += "/";
        }
        LOGGER.debug("Appending SHA1-hashed transfer ID '{}' to current destination '{}'.",
                new Object[] { pTransferId, sUrl });
        sUrl += CryptUtil.stringToSHA1(pTransferId);
        LOGGER.debug("Preparing destination at {}.", sUrl);

        result = new AbstractFile(new URL(sUrl));
        Configuration config = result.getConfiguration();
        String context = pContext.getUserId().getStringRepresentation() + " "
                + pContext.getGroupId().getStringRepresentation();
        LOGGER.debug("Adding repository context {} to custom access protocol configuration.", context);
        config.setProperty("repository.context", context);
        result = new AbstractFile(new URL(sUrl), config);

        //check if destination exists and create it if required
        if (result.exists()) {
            LOGGER.info("Destination at '{}' already exists.", sUrl);
        } else {//try to create destination
            result = AbstractFile.createDirectory(result);
        }

        //check destination
        if (result != null) {//destination could be obtained
            result.clearCachedValues();
            if (result.isReadable() && result.isWriteable()) {
                //everything is fine...return result
                return result;
            } else {
                //destination cannot be accessed
                LOGGER.error("Destination '{}' exists but is not read- or writeable", sUrl);
                result = null;
            }
        } else {
            LOGGER.warn("No result obtained from directory creation.");
        }
    } catch (MalformedURLException mue) {
        LOGGER.error("Failed to create valid destination URL for '" + sUrl + "' and transferId " + pTransferId,
                mue);
        result = null;
    } catch (AdalapiException ae) {
        LOGGER.error("Failed to check/create destination for '" + sUrl + "'", ae);
        result = null;
    }
    return result;
}