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.apache.kylin.engine.mr.CubingJob.java

/**
 * build fail because the metadata store has problem.
 * @param exception//  w w  w  .j a  va 2 s .c  o m
 */
@Override
protected void handleMetaDataPersistException(Exception exception) {
    String title = "[ERROR] - [" + getDeployEnvName() + "] - [" + getProjectName() + "] - "
            + CubingExecutableUtil.getCubeName(this.getParams());
    String content = ExecutableConstants.NOTIFY_EMAIL_TEMPLATE;
    final String UNKNOWN = "UNKNOWN";
    String errMsg = null;
    if (exception != null) {
        final StringWriter out = new StringWriter();
        exception.printStackTrace(new PrintWriter(out));
        errMsg = out.toString();
    }

    content = content.replaceAll("\\$\\{job_name\\}", getName());
    content = content.replaceAll("\\$\\{result\\}", ExecutableState.ERROR.toString());
    content = content.replaceAll("\\$\\{env_name\\}", getDeployEnvName());
    content = content.replaceAll("\\$\\{project_name\\}", getProjectName());
    content = content.replaceAll("\\$\\{cube_name\\}", CubingExecutableUtil.getCubeName(this.getParams()));
    content = content.replaceAll("\\$\\{source_records_count\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{start_time\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{duration\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{mr_waiting\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{last_update_time\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{submitter\\}", StringUtil.noBlank(getSubmitter(), "missing submitter"));
    content = content.replaceAll("\\$\\{error_log\\}",
            Matcher.quoteReplacement(StringUtil.noBlank(errMsg, "no error message")));

    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        content = content.replaceAll("\\$\\{job_engine\\}", inetAddress.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.warn(e.getLocalizedMessage(), e);
    }
    sendMail(Pair.of(title, content));
}

From source file:server.Wso2EventServer.java

public String getResourceFilePath(String testCaseFolderName, String resourceFileName) {
    String relativeFilePath = "../files/configs/" + resourceFileName;
    return relativeFilePath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator));
}

From source file:ddf.ldap.ldaplogin.SslLdapLoginModule.java

protected boolean doLogin() throws LoginException {

    // --------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP -------------
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);

    try {/*  ww  w.  j  ava2  s.  c o m*/
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        LOGGER.debug("Exception while handling login.", ioException);
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        LOGGER.debug("Exception while handling login.", unsupportedCallbackException);
        throw new LoginException(
                unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }

    user = ((NameCallback) callbacks[0]).getName();
    if (user == null) {
        return false;
    }
    user = user.trim();
    validateUsername(user);

    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();

    // If either a username or password is specified don't allow authentication = "none".
    // This is to prevent someone from logging into Karaf as any user without providing a
    // valid password (because if authentication = none, the password could be any
    // value - it is ignored).
    // Username is not checked in this conditional because a null username immediately exits
    // this method.
    if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) {
        LOGGER.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        setBindMethod(DEFAULT_AUTHENTICATION);
    }

    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }

    // ---------------------------------------------------------------------
    // RESET OBJECT STATE AND DECLARE LOCAL VARS
    principals = new HashSet<>();
    Connection connection;
    String userDn;
    // ---------------------------------------------------------------------

    // ------------- CREATE CONNECTION #1 ----------------------------------
    try {
        connection = ldapConnectionPool.borrowObject();
    } catch (Exception e) {
        LOGGER.info("Unable to obtain ldap connection from pool", e);
        return false;
    }
    try {

        if (connection != null) {
            // ------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindRequest request;
                switch (bindMethod) {
                case "Simple":
                    request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                    break;
                case "SASL":
                    request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword);
                    break;
                case "GSSAPI SASL":
                    request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword);
                    ((GSSAPISASLBindRequest) request).setRealm(realm);
                    ((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress);
                    break;
                case "Digest MD5 SASL":
                    request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword);
                    ((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH);
                    ((DigestMD5SASLBindRequest) request).getQOPs().clear();
                    ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF);
                    ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT);
                    ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH);
                    if (StringUtils.isNotEmpty(realm)) {
                        ((DigestMD5SASLBindRequest) request).setRealm(realm);
                    }
                    break;
                default:
                    request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                    break;
                }
                LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
                BindResult bindResult = connection.bind(request);

                if (!bindResult.isSuccess()) {
                    LOGGER.debug("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.debug("Unable to bind to LDAP server.", e);
                return false;
            }
            LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
            // --------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
            SearchScope scope;
            scope = userSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
            userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            userFilter = userFilter.replace("\\", "\\\\");
            LOGGER.trace("Performing LDAP query for user: {} at {} with filter {}", user, userBaseDN,
                    userFilter);
            try (ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter)) {
                while (entryReader.hasNext() && entryReader.isReference()) {
                    LOGGER.debug("Referral ignored while searching for user {}", user);
                    entryReader.readReference();
                }
                if (!entryReader.hasNext()) {
                    LOGGER.info("User {} not found in LDAP.", user);
                    return false;
                }
                SearchResultEntry searchResultEntry = entryReader.readEntry();

                userDn = searchResultEntry.getName().toString();

            } catch (LdapException | SearchResultReferenceIOException e) {
                LOGGER.info("Unable to read contents of LDAP user search.", e);
                return false;
            }

            // ----- BIND #2 (USER DISTINGUISHED NAME AND PASSWORD) ------------
            // Validate user's credentials.
            try {
                LOGGER.trace("Attempting LDAP bind for user: {}", userDn);
                BindResult bindResult = connection.bind(userDn, tmpPassword);

                if (!bindResult.isSuccess()) {
                    LOGGER.info("Bind failed");
                    return false;
                }
            } catch (Exception e) {
                LOGGER.info("Unable to bind user: {} to LDAP server.", userDn, e);
                return false;
            }

            LOGGER.trace("LDAP bind successful for user: {}", userDn);

            // ---------- ADD USER AS PRINCIPAL --------------------------------
            principals.add(new UserPrincipal(user));

            // ----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
                BindResult bindResult = connection.bind(connectionUsername, connectionPassword);

                if (!bindResult.isSuccess()) {
                    LOGGER.info("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.info("Unable to bind to LDAP server.", e);
                return false;
            }
            LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);

            // --------- SEARCH #3, GET ROLES ------------------------------
            scope = roleSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
            roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn));
            roleFilter = roleFilter.replace("\\", "\\\\");
            LOGGER.trace(
                    "Performing LDAP query for roles for user: {} at {} with filter {} for role attribute {}",
                    user, roleBaseDN, roleFilter, roleNameAttribute);

            // ------------- ADD ROLES AS NEW PRINCIPALS -------------------
            try (ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter,
                    roleNameAttribute)) {
                SearchResultEntry entry;
                while (entryReader.hasNext()) {
                    if (entryReader.isEntry()) {
                        entry = entryReader.readEntry();
                        Attribute attr = entry.getAttribute(roleNameAttribute);
                        if (attr == null) {
                            throw new LoginException("No attributes returned for [" + roleNameAttribute + " : "
                                    + roleBaseDN + "]");
                        }
                        for (ByteString role : attr) {
                            principals.add(new RolePrincipal(role.toString()));
                        }
                    } else {
                        // Got a continuation reference.
                        final SearchResultReference ref = entryReader.readReference();
                        LOGGER.debug("Skipping result reference: {}", ref.getURIs());
                    }
                }
            } catch (Exception e) {
                LOGGER.debug("Exception while getting roles for [" + user + "].", e);
                throw new LoginException("Can't get roles for [" + user + "]: " + e.getMessage());
            }
        } else {
            LOGGER.trace("LDAP Connection was null could not authenticate user.");
            return false;
        }

        return true;
    } finally {
        ldapConnectionPool.returnObject(connection);
    }
}

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

private String detokenizeParameters(String str) {
    Set<String> variableTokens = ActionUtils.getVariableNames(action);
    int tokenCounter = 0;
    for (String var : variableTokens) {
        str = str.replaceAll(Pattern.quote("${" + (tokenCounter++) + "}"),
                Matcher.quoteReplacement("${" + var + "}"));
    }/*from   www .  ja v a2  s  .  com*/
    return str;
}

From source file:org.apache.sqoop.connector.idf.CSVIntermediateDataFormat.java

private String escapeStrings(String orig) {
    if (orig == null) {
        return NULL_STRING;
    }/*www  .  j a va 2 s.co  m*/

    int j = 0;
    String replacement = orig;
    try {
        for (j = 0; j < replacements.length; j++) {
            replacement = replacement.replaceAll(getRegExp(originals[j]),
                    Matcher.quoteReplacement(replacements[j]));
        }
    } catch (Exception e) {
        throw new SqoopException(IntermediateDataFormatError.INTERMEDIATE_DATA_FORMAT_0002,
                orig + "  " + replacement + "  " + String.valueOf(j) + "  " + e.getMessage());
    }
    StringBuilder builder = new StringBuilder();
    builder.append(QUOTE_CHARACTER).append(replacement).append(QUOTE_CHARACTER);
    return builder.toString();
}

From source file:com.dtolabs.rundeck.core.dispatcher.DataContextUtils.java

/**
 * Replace the embedded  properties of the form '${key.name}' in the input Strings with the value from the data
 * context/* ww  w .  ja va 2 s . co m*/
 *
 *
 * @param input input string
 * @param data  data context map
 *              @param converter converter to encode/convert the expanded values
 *
 * @param failOnUnexpanded
 * @return string with values substituted, or original string
 */
public static String replaceDataReferences(final String input, final Map<String, Map<String, String>> data,
        final Converter<String, String> converter, boolean failOnUnexpanded, boolean blankIfUnexpanded) {
    if (null == data) {
        return input;
    }
    final Pattern p = Pattern.compile(PROPERTY_REF_REGEX);
    final Matcher m = p.matcher(input);
    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        final String key = m.group(1);
        final String nm = m.group(2);
        if (null != key && null != nm && null != data.get(key) && null != data.get(key).get(nm)) {
            String value = data.get(key).get(nm);
            if (null != converter) {
                value = converter.convert(value);
            }
            m.appendReplacement(sb, Matcher.quoteReplacement(value));
        } else if (failOnUnexpanded && null != key && null != nm
                && (null == data.get(key) || null == data.get(key).get(nm))) {
            throw new UnresolvedDataReferenceException(input, m.group());
        } else if (blankIfUnexpanded) {
            m.appendReplacement(sb, "");
        } else {
            String value = m.group(0);
            if (null != converter) {
                value = converter.convert(value);
            }
            m.appendReplacement(sb, Matcher.quoteReplacement(value));
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.predic8.membrane.core.rules.SOAPProxy.java

public void configure() throws Exception {

    parseWSDL();//from   w  w  w .  ja va  2 s .c om

    // remove previously added interceptors
    for (; automaticallyAddedInterceptorCount > 0; automaticallyAddedInterceptorCount--)
        interceptors.remove(0);

    // add interceptors (in reverse order) to position 0.

    WebServiceExplorerInterceptor sui = new WebServiceExplorerInterceptor();
    sui.setWsdl(wsdl);
    sui.setPortName(portName);
    interceptors.add(0, sui);
    automaticallyAddedInterceptorCount++;

    boolean hasPublisher = getInterceptorOfType(WSDLPublisherInterceptor.class) != null;
    if (!hasPublisher) {
        WSDLPublisherInterceptor wp = new WSDLPublisherInterceptor();
        wp.setWsdl(wsdl);
        interceptors.add(0, wp);
        automaticallyAddedInterceptorCount++;
    }

    WSDLInterceptor wsdlInterceptor = getInterceptorOfType(WSDLInterceptor.class);
    boolean hasRewriter = wsdlInterceptor != null;
    if (!hasRewriter) {
        wsdlInterceptor = new WSDLInterceptor();
        interceptors.add(0, wsdlInterceptor);
        automaticallyAddedInterceptorCount++;
    }
    if (key.getPath() != null) {
        final String keyPath = key.getPath();
        final String name = URLUtil.getName(router.getUriFactory(), keyPath);
        wsdlInterceptor.setPathRewriter(new PathRewriter() {
            @Override
            public String rewrite(String path2) {
                try {
                    if (path2.contains("://")) {
                        path2 = new URL(new URL(path2), keyPath).toString();
                    } else {
                        Matcher m = relativePathPattern.matcher(path2);
                        path2 = m.replaceAll("./" + name + "?");
                    }
                } catch (MalformedURLException e) {
                }
                return path2;
            }
        });
    }

    if (hasRewriter && !hasPublisher)
        log.warn(
                "A <soapProxy> contains a <wsdlRewriter>, but no <wsdlPublisher>. Probably you want to insert a <wsdlPublisher> just after the <wsdlRewriter>. (Or, if this is a valid use case, please notify us at "
                        + Constants.PRODUCT_CONTACT_EMAIL + ".)");

    if (targetPath != null) {
        RewriteInterceptor ri = new RewriteInterceptor();
        ri.setMappings(Lists.newArrayList(new RewriteInterceptor.Mapping("^" + Pattern.quote(key.getPath()),
                Matcher.quoteReplacement(targetPath), "rewrite")));
        interceptors.add(0, ri);
        automaticallyAddedInterceptorCount++;
    }
}

From source file:org.apache.synapse.mediators.experimental.MockFactoryMediator.java

/**
 * Goes through SynapsePath argument list, evaluating each by calling stringValueOf and returns a HashMap String, String
 * array where each item will contain a hash map with key "evaluated expression" and value "SynapsePath type".
 *
 * @param synCtx//from   ww  w .  j  a v a 2 s  .com
 * @return
 */
private HashMap<String, String>[] getArgValues(MessageContext synCtx) {
    HashMap<String, String>[] argValues = new HashMap[pathArgumentList.size()];
    HashMap<String, String> valueMap;
    String value = "";
    for (int i = 0; i < pathArgumentList.size(); ++i) { /*ToDo use foreach*/
        Argument arg = pathArgumentList.get(i);
        if (arg.getValue() != null) {
            value = arg.getValue();
            if (!isXML(value)) {
                value = StringEscapeUtils.escapeXml(value);
            }
            value = Matcher.quoteReplacement(value);
        } else if (arg.getExpression() != null) {
            value = arg.getExpression().stringValueOf(synCtx);
            if (value != null) {
                // XML escape the result of an expression that produces a literal, if the target format
                // of the payload is XML.
                if (!isXML(value) && !arg.getExpression().getPathType().equals(SynapsePath.JSON_PATH)
                        && XML_TYPE.equals(getType())) {
                    value = StringEscapeUtils.escapeXml(value);
                }
                value = Matcher.quoteReplacement(value);
            } else {
                value = "";
            }
        } else {
            handleException("Unexpected arg type detected", synCtx);
        }
        //value = value.replace(String.valueOf((char) 160), " ").trim();
        valueMap = new HashMap<String, String>();
        if (null != arg.getExpression()) {
            valueMap.put(value, arg.getExpression().getPathType());
        } else {
            valueMap.put(value, SynapsePath.X_PATH);
        }
        argValues[i] = valueMap;
    }
    return argValues;
}

From source file:org.wso2.am.integration.test.utils.base.AMIntegrationBaseTest.java

/**
 * @param relativeFilePath/*from w  ww .  j a v  a2  s. c  om*/
 * @throws Exception
 */

protected void loadAPIMConfigurationFromClasspath(String relativeFilePath) throws Exception {
    relativeFilePath = relativeFilePath.replaceAll("[\\\\/]", Matcher.quoteReplacement(File.separator));

    OMElement synapseConfig = apimTestCaseUtils.loadResource(relativeFilePath);
    updateAPIMConfiguration(synapseConfig);

}

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

@Test
public void test_Controller_Jsp_Model() throws IOException {
    String commonPath = "src/main/webapp/WEB-INF/sandbox/apsadmin/jsp/cat".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(3, actualFiles.size());
    this.compareFiles(actualFiles);

    //----/*from  w ww  .jav a2 s .  c om*/

    commonPath = "src/main/webapp/WEB-INF/sandbox/apsadmin/jsp/common/layouts".replaceAll("/",
            Matcher.quoteReplacement(File.separator));

    actualPath = ACTUAL_BASE_FOLDER + commonPath;

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

    FileFilter excludeSubfolders = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            if (pathname.isDirectory() && !pathname.getName().equals("layouts"))
                return false;
            return true;
        }
    };

    actualFiles = this.searchFiles(actualDir, excludeSubfolders);
    Assert.assertEquals(0, actualFiles.size()); //no submenu
    //this.compareFiles(actualFiles);
}