Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java

/**
 * Generates Maven archetype from existing project. This is lightweight version of <code>mvn archetype:create-from-project</code>.
 *
 * @param projectDir directory of source project which will be converted to Maven Archetype
 * @param projectPom pom file of source  project
 * @param archetypeDir output directory where Maven Archetype project will be created
 * @param clean remove the archetypeDir entirely?
 * @throws IOException/*from  ww  w  . j  a  v  a2  s.c o  m*/
 */
private void generateArchetype(File projectDir, File projectPom, File archetypeDir, boolean clean,
        List<String> dirs) throws IOException {
    LOG.debug("Generating archetype from {} to {}", projectDir.getName(), archetypeDir.getCanonicalPath());

    // add to dirs
    dirs.add(archetypeDir.getName());

    File srcDir = new File(projectDir, "src/main");
    File testDir = new File(projectDir, "src/test");
    File outputSrcDir = new File(archetypeDir, "src");
    File outputGitIgnoreFile = new File(archetypeDir, ".gitignore");

    if (clean) {
        LOG.debug("Removing generated archetype dir {}", archetypeDir);
        FileUtils.deleteDirectory(archetypeDir);
    } else if (outputSrcDir.exists() && outputGitIgnoreFile.exists()
            && fileIncludesLine(outputGitIgnoreFile, "src")) {
        LOG.debug("Removing generated src dir {}", outputSrcDir);
        FileUtils.deleteDirectory(outputSrcDir);
        if (outputSrcDir.exists()) {
            throw new RuntimeException("The projectDir " + outputSrcDir + " should not exist!");
        }
    }

    // Main dir for archetype resources - copied from original maven project. Sources will have
    // package names replaced with variable placeholders - to make them parameterizable during
    // mvn archetype:generate
    File archetypeOutputDir = new File(archetypeDir, "src/main/resources/archetype-resources");
    // optional archetype-metadata.xml provided by source project
    //        File metadataXmlFile = new File(projectDir, "archetype-metadata.xml");
    // target archetype-metadata.xml file. it'll end in resources-filtered, so most of variables will be replaced
    // during the build of archetype project
    File metadataXmlOutFile = new File(archetypeDir,
            "src/main/resources-filtered/META-INF/maven/archetype-metadata.xml");

    Replacement replaceFunction = new IdentityReplacement();

    File mainSrcDir = null;
    for (String it : ArchetypeUtils.sourceCodeDirNames) {
        File dir = new File(srcDir, it);
        if (dir.exists()) {
            mainSrcDir = dir;
            break;
        }
    }

    if (mainSrcDir != null) {
        // lets find the first projectDir which contains more than one child
        // to find the root-most package
        File rootPackage = archetypeUtils.findRootPackage(mainSrcDir);

        if (rootPackage != null) {
            String packagePath = archetypeUtils.relativePath(mainSrcDir, rootPackage);
            String packageName = packagePath.replaceAll(Pattern.quote("/"), ".");
            LOG.debug("Found root package in {}: {}", mainSrcDir, packageName);
            final String regex = packageName.replaceAll(Pattern.quote("."), "\\.");

            replaceFunction = new Replacement() {
                @Override
                public String replace(String token) {
                    return token.replaceAll(regex, "\\${package}");
                }
            };

            // lets recursively copy files replacing the package names
            File outputMainSrc = new File(archetypeOutputDir,
                    archetypeUtils.relativePath(projectDir, mainSrcDir));
            copyCodeFiles(rootPackage, outputMainSrc, replaceFunction);

            // tests copied only if there's something in "src/main"

            File testSrcDir = null;
            for (String it : ArchetypeUtils.sourceCodeDirNames) {
                File dir = new File(testDir, it);
                if (dir.exists()) {
                    testSrcDir = dir;
                    break;
                }
            }

            if (testSrcDir != null) {
                File rootTestDir = new File(testSrcDir, packagePath);
                File outputTestSrc = new File(archetypeOutputDir,
                        archetypeUtils.relativePath(projectDir, testSrcDir));
                if (rootTestDir.exists()) {
                    copyCodeFiles(rootTestDir, outputTestSrc, replaceFunction);
                } else {
                    copyCodeFiles(testSrcDir, outputTestSrc, replaceFunction);
                }
            }
        }
    }

    // now copy pom.xml
    createArchetypeDescriptors(projectPom, archetypeDir, new File(archetypeOutputDir, "pom.xml"),
            metadataXmlOutFile, replaceFunction);

    // now lets copy all non-ignored files across
    copyOtherFiles(projectDir, projectDir, archetypeOutputDir, replaceFunction);

    // add missing .gitignore if missing
    if (!outputGitIgnoreFile.exists()) {
        ArchetypeUtils.writeGitIgnore(outputGitIgnoreFile);
    }
}

From source file:com.github.wnameless.spring.routing.RoutingPathResolver.java

private String computeRegexPath(String path) {
      path = Regexs.escapeSpecialCharacters(path, PLACEHOLDER, PATH_VAR, ANT_AA, ANT_A, ANT_Q);
      Matcher m = PATH_VAR.matcher(path);
      while (m.find()) {
          String match = m.group();
          path = path.replaceFirst(Pattern.quote(match), "[^/]+");
      }//from   w w  w. java 2s  .com
      m = ANT_AA.matcher(path);
      while (m.find()) {
          String match = m.group();
          path = path.replaceFirst(Pattern.quote(match), ".\"");
      }
      m = ANT_A.matcher(path);
      while (m.find()) {
          String match = m.group();
          path = path.replaceFirst(Pattern.quote(match), "[^/]*");
      }
      m = ANT_Q.matcher(path);
      while (m.find()) {
          String match = m.group();
          path = path.replaceFirst(Pattern.quote(match), ".");
      }
      path = path.replaceAll(Pattern.quote("\""), "*");

      // the first slash of an URL can be omitted
      path = path.startsWith("/") ? path = "/?" + path.substring(1) : "/?" + path;
      // the last slash of an URL is optional if user not mentions
      if (!path.endsWith("/"))
          path = path + "/?";

      return path;
  }

From source file:com.mediaworx.xmlutils.XmlHelper.java

/**
 * Parses the XML content of the file at the given path using the default encoding (UTF-8). Empty text nodes or
 * text nodes containing whitespace only are removed. If a replacement map is provided, each key in the map is
 * replaced by the corresponding value in the file's content.
 *
 * @param file the file containing the XML
 * @param replacements Map containing replacement strings, key: string to be replaced, value: replacement string (if the map is null, no replacements are made)
 * @param encoding  the encoding to be used to parse the file (must be a valid encoding like "UTF-8")
 * @return  the parsed XML document// w  w w.j a va2  s.c  o m
 * @throws IOException  if there's a problem accessing the file
 * @throws SAXException if the file content can't be parsed
 */
public Document parseFile(File file, Map<String, String> replacements, String encoding)
        throws IOException, SAXException {
    String fileContent = readFile(file, encoding);

    if (replacements != null) {
        for (String search : replacements.keySet()) {
            String replace = replacements.get(search);
            fileContent = fileContent.replaceAll(Pattern.quote(search), Matcher.quoteReplacement(replace));
        }
    }
    StringReader reader = new StringReader(fileContent);
    Document document = builder.parse(new InputSource(reader));
    cleanEmptyTextNodes(document);
    return document;
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtil.java

String replaceDnsPattern(String hostnameTemplate, ServiceTemplateComponent component) {
    List<Network> networks = ServiceTemplateClientUtil.findManagementNetworks(component);
    if (networks != null) {
        StaticNetworkConfiguration config = null;
        for (Network network : networks) {
            if (network.isStatic() && network.getStaticNetworkConfiguration() != null) {
                config = network.getStaticNetworkConfiguration();
                break;
            }//from   w w  w.j a v  a 2s.  c om
        }

        if (config != null && !StringUtils.isBlank(config.getIpAddress())) {
            if (StringUtils.isBlank(config.getPrimaryDns()) && StringUtils.isBlank(config.getSecondaryDns())) {
                throw new LocalizedWebApplicationException(Response.Status.BAD_REQUEST,
                        AsmManagerMessages.noDnsServersForManagementNetwork(component.getName()));
            }
            String hostname = dnsUtil.reverseLookup(config.getIpAddress(), config.getPrimaryDns(),
                    config.getSecondaryDns());
            if (hostname != null) {
                hostname = stripDnsSuffix(hostname, config.getDnsSuffix());
                return hostnameTemplate.replaceAll(Pattern.quote(DNS_PATTERN), hostname.toLowerCase());
            } else {
                throw new LocalizedWebApplicationException(Response.Status.BAD_REQUEST, AsmManagerMessages
                        .reverseDnsLookupFailed(config.getIpAddress(), config.getPrimaryDns()));
            }
        }
    }

    throw new LocalizedWebApplicationException(Response.Status.BAD_REQUEST,
            AsmManagerMessages.staticIpRequiredForDnsHostnameTemplate());
}

From source file:com.bluexml.side.clazz.service.alfresco.CommonServices.java

public static void log(EObject o, String message) {
    message = message.replaceFirst(Pattern.quote("{object}"), o.toString())
            .replaceFirst(Pattern.quote("{date}"), new Date().toString());
    System.out.println("CommonServices.log() :" + message);
}

From source file:com.google.appengine.tck.logservice.RequestLogsTest.java

@Test
@InSequence(20)/*  ww w.  jav  a  2s.  com*/
public void testCombined() throws Exception {
    String regexp = REGEX_IP4 + " - - \\[" + REGEX_TIMESTAMP + "\\] \""
            + Pattern.quote("GET " + REQUEST_1_RESOURCE + " HTTP/1.1") + "\" [0-9]+ [0-9]+ .*";
    assertRegexpMatches(regexp, getRequestLogs1().getCombined());
}

From source file:com.concursive.connect.web.portal.PortalUtils.java

public static String[] getPageParameters(PortletRequest request) {
    String paramsString = (String) request.getAttribute("portletParams");
    if (paramsString != null) {
        String[] params = paramsString.trim().split(Pattern.quote("_cc_"));
        if (params != null && params.length > 0) {
            return params;
        }//from w w w . ja v a  2  s . c o  m
    }
    return null;
}

From source file:org.loklak.api.server.push.GeoJsonPushServlet.java

/**
 * For each member m in properties, if it exists in mapRules, perform these conversions :
 *   - m:c -> keep value, change key m to c
 *   - m:c.d -> insert/update json object of key c with a value {d : value}
 * @param mapRules/*  w w w  . j a  v  a 2s . c o m*/
 * @param properties
 * @return mappedProperties
 */
private Map<String, Object> convertMapRulesProperties(Map<String, List<String>> mapRules,
        Map<String, Object> properties) {
    Map<String, Object> root = new HashMap<>();
    Iterator<Map.Entry<String, Object>> it = properties.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, Object> pair = it.next();
        String key = pair.getKey();
        if (mapRules.containsKey(key)) {
            for (String newField : mapRules.get(key)) {
                if (newField.contains(".")) {
                    String[] deepFields = newField.split(Pattern.quote("."));
                    Map<String, Object> currentLevel = root;
                    for (int lvl = 0; lvl < deepFields.length; lvl++) {
                        if (lvl == deepFields.length - 1) {
                            currentLevel.put(deepFields[lvl], pair.getValue());
                        } else {
                            if (currentLevel.get(deepFields[lvl]) == null) {
                                Map<String, Object> tmp = new HashMap<>();
                                currentLevel.put(deepFields[lvl], tmp);
                            }
                            currentLevel = (Map<String, Object>) currentLevel.get(deepFields[lvl]);
                        }
                    }
                } else {
                    root.put(newField, pair.getValue());
                }
            }
        }
    }
    return root;
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtil.java

public static String replaceNumPattern(String hostnameTemplate, Set<String> allHostnames) {
    // we might already have the same hostname with auto-generated numbers. There is no way
    // to keep the counter updated, thus we have to check for dup every time we replace
    // ${num} with next gen number.
    String hostnameWithNumPattern = hostnameTemplate;

    int hostNameCounter = 0;
    while (hostnameWithNumPattern != null && hostNameCounter <= allHostnames.size()) {
        while (hostnameWithNumPattern.contains(NUM_PATTERN)) {
            hostNameCounter++;/*w  w w .j  ava  2 s  .  com*/
            hostnameWithNumPattern = hostnameWithNumPattern.replaceFirst(Pattern.quote(NUM_PATTERN),
                    String.valueOf(hostNameCounter));
        }

        if (!allHostnames.contains(hostnameWithNumPattern)) {
            hostnameTemplate = hostnameWithNumPattern;
            break;
        } else {
            // number pattern was already used, try again with next gen, reset the original name to get pattern back
            hostnameWithNumPattern = hostnameTemplate;
        }
    }
    return hostnameTemplate;
}

From source file:brainflow.app.presentation.controls.FileObjectGroupSelector.java

private static String globToRegexPattern(final String glob) throws PatternSyntaxException {
    /* Stack to keep track of the parser mode: */
    /* "--" : Base mode (first on the stack)   */
    /* "[]" : Square brackets mode "[...]"     */
    /* "{}" : Curly braces mode "{...}"        */
    final Deque<String> parserMode = new ArrayDeque<String>();
    parserMode.push("--"); // base mode

    final int globLength = glob.length();
    int index = 0; // index in glob

    /* equivalent REGEX expression to be compiled */
    final StringBuilder t = new StringBuilder();

    while (index < globLength) {
        char c = glob.charAt(index++);

        if (c == '\\') {
            /***********************
             * (1) ESCAPE SEQUENCE *//from w  w  w . j a  va  2  s .c  om
             ***********************/

            if (index == globLength) {
                /* no characters left, so treat '\' as literal char */
                t.append(Pattern.quote("\\"));
            } else {
                /* read next character */
                c = glob.charAt(index);
                final String s = c + "";

                if (("--".equals(parserMode.peek()) && "\\[]{}?*".contains(s))
                        || ("[]".equals(parserMode.peek()) && "\\[]{}?*!-".contains(s))
                        || ("{}".equals(parserMode.peek()) && "\\[]{}?*,".contains(s))) {
                    /* escape the construct char */
                    index++;
                    t.append(Pattern.quote(s));
                } else {
                    /* treat '\' as literal char */
                    t.append(Pattern.quote("\\"));
                }
            }
        } else if (c == '*') {
            /************************
             * (2) GLOB PATTERN '*' *
             ************************/

            /* create non-capturing group to match zero or more characters */
            t.append(".*");
        } else if (c == '?') {
            /************************
             * (3) GLOB PATTERN '?' *
             ************************/

            /* create non-capturing group to match exactly one character */
            t.append('.');
        } else if (c == '[') {
            /****************************
             * (4) GLOB PATTERN "[...]" *
             ****************************/

            /* opening square bracket '[' */
            /* create non-capturing group to match exactly one character */
            /* inside the sequence */
            t.append('[');
            parserMode.push("[]");

            /* check for negation character '!' immediately after */
            /* the opening bracket '[' */
            if ((index < globLength) && (glob.charAt(index) == '!')) {
                index++;
                t.append('^');
            }
        } else if ((c == ']') && "[]".equals(parserMode.peek())) {
            /* closing square bracket ']' */
            t.append(']');
            parserMode.pop();
        } else if ((c == '-') && "[]".equals(parserMode.peek())) {
            /* character range '-' in "[...]" */
            t.append('-');
        } else if (c == '{') {
            /****************************
             * (5) GLOB PATTERN "{...}" *
             ****************************/

            /* opening curly brace '{' */
            /* create non-capturing group to match one of the */
            /* strings inside the sequence */
            t.append("(?:(?:");
            parserMode.push("{}");
        } else if ((c == '}') && "{}".equals(parserMode.peek())) {
            /* closing curly brace '}' */
            t.append("))");
            parserMode.pop();
        } else if ((c == ',') && "{}".equals(parserMode.peek())) {
            /* comma between strings in "{...}" */
            t.append(")|(?:");
        } else {
            /*************************
             * (6) LITERAL CHARACTER *
             *************************/

            /* convert literal character to a regex string */
            t.append(Pattern.quote(c + ""));
        }
    }
    /* done parsing all chars of the source pattern string */

    /* check for mismatched [...] or {...} */
    if ("[]".equals(parserMode.peek()))
        throw new PatternSyntaxException("Cannot find matching closing square bracket ] in GLOB expression",
                glob, -1);

    if ("{}".equals(parserMode.peek()))
        throw new PatternSyntaxException("Cannot find matching closing curly brace } in GLOB expression", glob,
                -1);

    return t.toString();
}