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.echocat.jomon.resources.optimizing.MakeCssResourcePathAbsoluteOptimizer.java

@Nonnull
protected String handleCssBody(@Nonnull String oldCssBody, @Nonnull String uri,
        @Nonnull OptimizationContext context) throws Exception {
    final Matcher matcher = PATTERN.matcher(oldCssBody);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        final String oldMatch = matcher.group();
        final String oldUri = matcher.group(3) != null ? matcher.group(3) : matcher.group(2);
        final String uriContent = matcher.group(1) != null ? matcher.group(1) : oldUri;

        final String newUri = newUri(uri, oldUri, context);
        if (newUri != null && !oldUri.equals(newUri)) {
            final String newReplacement = Matcher.quoteReplacement(oldMatch.replace(uriContent, newUri));
            matcher.appendReplacement(sb, newReplacement);
        }//from  ww  w .j av  a  2 s . c  om
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.slc.sli.ingestion.tenant.TenantPopulator.java

/**
 *
 * Create the landing zone directory for the parent landing zone
 *
 *//*from w w w . ja  v  a 2  s. c  o m*/
private void createParentLzDirectory() {
    String lzPath = Matcher.quoteReplacement(parentLandingZoneDir);
    File lzDirectory = new File(lzPath);
    if (!lzDirectory.mkdir()) {
        LOG.debug("Failed to mkdir: {}", lzDirectory.getPath());
    }
    if (!lzDirectory.setReadable(true, false)) {
        LOG.debug("Failed to setReadable: {}", lzDirectory.getPath());
    }
    if (!lzDirectory.setWritable(true, false)) {
        LOG.debug("Failed to setWritable: {}", lzDirectory.getPath());
    }
}

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

/**
 * removes existing target attribute in the anchor tag and adds target="_blank"
 * /*  ww w  .j  a v  a  2 s.  c o  m*/
 * @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();
}

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

public static String resolveFile(final Context context, final RepoFile file,
        Map<PropertyKey, Property> resolved, Map<String, String> passwords) throws ConfigException {
    boolean encrypt = false;
    String pass = "";
    if (file.isEncrypted()) {
        pass = passwords.get(file.getSecurityProfile().getName());
        if (null == pass || !file.getSecurityProfile().isSecretValid(pass)) {
            pass = file.getSecurityProfile().getDecodedPassword();
            encrypt = true;//ww w. j  a va2  s .  c  om
        }

        file.decryptFile(pass);
    }

    Map<String, Property> propertyMap = new HashMap<>();
    Map<String, PropertyKey> keyMap = new HashMap<>();
    resolved.keySet().forEach(k -> {
        propertyMap.put(k.getKey(), resolved.get(k));
        keyMap.put(k.getKey(), k);
    });

    String fileContent = file.getContent();
    String patternString = "(?i)\\$\\{\\s*\\b(" + StringUtils.join(propertyMap.keySet(), "|") + ")\\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 = propertyMap.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())) {
                RepoFile injectFile = context.resolveFullContextFilePath(property.getAbsoluteFilePath());
                if (null == injectFile)
                    value = "[ ERROR: No file resolved ]";
                else
                    value = resolveFile(context, injectFile, resolved, passwords);
            } else {
                if (property.isEncrypted()) {
                    String spName = keyMap.get(key).getSecurityProfile().getName();
                    if (passwords.containsKey(spName))
                        property.decryptValue(passwords.get(spName));
                }
                value = setValue(property);
            }
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
    }

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

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

    if (encrypt)
        fileContent = Encryption.encrypt(file.getSecurityProfile().getCipher(), fileContent, pass);

    return fileContent;
}

From source file:de.uzk.hki.da.convert.CLIConversionStrategy.java

/**
 * Convert file./*from  w  ww .  ja  v a  2 s . c  o m*/
 *
 * @param ci the ci
 * @return the list
 * @throws FileNotFoundException the file not found exception
 */
@Override
public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) throws FileNotFoundException {
    if (pkg == null)
        throw new IllegalStateException("Package not set");
    Path.make(wa.dataPath(), object.getNameOfLatestBRep(), ci.getTarget_folder()).toFile().mkdirs();

    String[] commandAsArray = assemble(wa, ci, object.getNameOfLatestBRep());
    if (!cliConnector.execute(commandAsArray))
        throw new RuntimeException("convert did not succeed");

    String targetSuffix = ci.getConversion_routine().getTarget_suffix();
    if (targetSuffix.equals("*"))
        targetSuffix = FilenameUtils.getExtension(toAbsolutePath(wa.dataPath(), ci.getSource_file()));
    DAFile result = new DAFile(object.getNameOfLatestBRep(),
            ci.getTarget_folder() + "/"
                    + FilenameUtils.removeExtension(Matcher.quoteReplacement(
                            FilenameUtils.getName(toAbsolutePath(wa.dataPath(), ci.getSource_file()))))
                    + "." + targetSuffix);

    Event e = new Event();
    e.setType("CONVERT");
    e.setDetail(StringUtilities.createString(commandAsArray));
    e.setSource_file(ci.getSource_file());
    e.setTarget_file(result);
    e.setDate(new Date());

    List<Event> results = new ArrayList<Event>();
    results.add(e);
    return results;
}

From source file:com.codenvy.ide.git.VFSPermissionsFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    int tokenPlace;
    String lastTokenBeforePath = "/" + gitServerUriPrefix + "/";
    if ((tokenPlace = req.getRequestURL().indexOf(lastTokenBeforePath)) != -1) {
        //get path to project
        String url = req.getRequestURL().substring(tokenPlace + lastTokenBeforePath.length());
        url = url.replaceFirst("/info/refs", "");
        url = url.replaceFirst("/git-upload-pack", "");
        //adaptation to fs
        url = url.replaceAll("/", Matcher.quoteReplacement(File.separator));
        //search for dotVFS directory
        File projectDirectory = Paths.get(vfsRoot, url).toFile();
        String auth;/*from  w  w w  .j a  v  a 2 s  .c  om*/
        String userName = "";
        String password = "";
        if ((auth = req.getHeader("authorization")) != null) {
            //get encoded password phrase
            String userAndPasswordEncoded = auth.substring(6);
            // decode Base64 user:password
            String userAndPasswordDecoded = new String(Base64.decodeBase64(userAndPasswordEncoded));
            //get username and password separator ':'
            int betweenUserAndPassword = userAndPasswordDecoded.indexOf(':');
            //get username - it is before first ':'
            userName = userAndPasswordDecoded.substring(0, betweenUserAndPassword);
            //get password - it is after first ':'
            password = userAndPasswordDecoded.substring(betweenUserAndPassword + 1);
        }

        // Check if user authenticated and has permissions to project, or send response code 403
        boolean needLogout = false;
        String token = null;
        User user;
        try {
            if (!userName.isEmpty()) {
                if (password.equals("x-che")) { // internal SSO
                    token = userName;
                } else {
                    token = getToken(userName, password);
                    if (token == null) {
                        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                        return;
                    }
                    needLogout = true;
                }
                user = getUserBySSO(token);
                EnvironmentContext.getCurrent().setUser(user);
            }

            if (!hasAccessToItem(projectDirectory.getParentFile().getName(), projectDirectory.getName())) {
                if (!userName.isEmpty()) {
                    // Authenticated but no access
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else {
                    // Not authenticated, try again with credentials
                    ((HttpServletResponse) response).addHeader("Cache-Control", "private");
                    ((HttpServletResponse) response).addHeader("WWW-Authenticate", "Basic");
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return;
                }
            }
        } finally {
            if (needLogout) {
                logout();
            }
            EnvironmentContext.reset();
        }
    }
    chain.doFilter(req, response);
}

From source file:org.rhq.plugins.database.CustomTableRowDiscoveryComponent.java

/**
 * Format a message with {<key>} formatted replacement keys.
 *
 * @param  message the message to format
 * @param  key to replace; if null returns the message as-is
 *
 * @return the formatted text with variables replaced
 *//*from   w  w  w  .  j  a v  a  2s .  co m*/
public static String formatMessage(String message, String key) {
    if (key == null)
        return message;
    key = Matcher.quoteReplacement(key);
    message = message.replaceAll("\\{key\\}", key);
    return message;
}

From source file:pt.webdetails.cdf.dd.model.inst.writer.cdfrunjs.dashboard.CdfRunJsDashboardWriter.java

public void write(CdfRunJsDashboardWriteResult.Builder builder, CdfRunJsDashboardWriteContext ctx,
        Dashboard dash) throws ThingWriteException {
    assert dash == ctx.getDashboard();

    DashboardWcdfDescriptor wcdf = dash.getWcdf();

    // ------------

    String template;/*from   w w w  . ja  va 2 s  . c om*/
    try {
        template = this.readTemplate(wcdf);
    } catch (IOException ex) {
        throw new ThingWriteException("Could not read style template file.", ex);
    }

    template = ctx.replaceTokens(template);

    // ------------

    String footer;
    try {
        footer = Util.toString(
                CdeEnvironment.getPluginSystemReader().getFileInputStream(CdeConstants.RESOURCE_FOOTER));
    } catch (IOException ex) {
        throw new ThingWriteException("Could not read footer file.", ex);
    }

    // ------------

    String layout = ctx.replaceTokensAndAlias(this.writeLayout(ctx, dash));
    String components = ctx.replaceTokensAndAlias(this.writeComponents(ctx, dash));
    String content = writeContent(layout, components);
    String header = ctx.replaceTokens(writeHeaders(content, ctx));

    // Leave the DASHBOARD_HEADER_TAG to replace additional stuff on render.
    template = template
            .replaceAll(CdeConstants.DASHBOARD_HEADER_TAG,
                    Matcher.quoteReplacement(header) + CdeConstants.DASHBOARD_HEADER_TAG)
            .replaceAll(CdeConstants.DASHBOARD_FOOTER_TAG, Matcher.quoteReplacement(footer))
            .replaceAll(CdeConstants.DASHBOARD_CONTENT_TAG, Matcher.quoteReplacement(content));

    // Export
    builder.setTemplate(template).setHeader(header).setLayout(layout).setComponents(components)
            .setContent(content).setFooter(footer).setLoadedDate(ctx.getDashboard().getSourceDate());
}

From source file:com.anrisoftware.globalpom.textmatch.tokentemplate.DefaultTokensTemplate.java

private String escapeReplace(String replace) {
    return Matcher.quoteReplacement(replace);
}

From source file:org.clickframes.util.ClickframeUtils.java

public static String getFileSeparatorLiteral() {
    return Matcher.quoteReplacement(File.separator);
}