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:com.mercatis.lighthouse3.commons.commons.XmlMuncher.java

/**
 * This method translates an XPath expression into a regular expression that
 * matches on the path of an XML element iff the XPath expression would
 * match that element as well.//from   w  ww .j  a  v  a  2 s .com
 * <p/>
 * Note that only simple expressions on elements using *, /:, and //: are
 * supported.
 *
 * @param xpathExpression the XPath expression to translate
 * @return the regular expression equivalent to the XPath expression.
 * @throws XPathExpressionException in case of trouble with the XPath expression.
 */
private Pattern translateXPathExpressionToRegexp(String xpathExpression) throws XPathExpressionException {
    StringBuilder regularExpression = new StringBuilder("^");

    for (String token : this.tokenizeXPathExpression(xpathExpression)) {
        if (XPATH_DIRECT_CHILD.equals(token))
            regularExpression.append(Pattern.quote("/"));
        else if (XPATH_ANY_ELEMENT.equals(token))
            regularExpression.append("([A-Za-z0-9_:]+)");
        else if (XPATH_INDIRECT_CHILD.equals(token))
            regularExpression.append("(").append(Pattern.quote("/")).append("[A-Za-z0-9_:]*)+");
        else
            regularExpression.append("(").append(Pattern.quote(token)).append(")");
    }

    try {
        return Pattern.compile(regularExpression.toString());
    } catch (PatternSyntaxException e) {
        throw new XPathExpressionException(e);
    }
}

From source file:fr.dudie.acrachilisync.utils.IssueDescriptionReader.java

/**
 * Extracts the list of bug occurrences from the description.
 * /*from   w  ww . j av a 2  s. c  o  m*/
 * @param pDescription
 *            the issue description
 * @param pStacktraceMD5
 *            the stacktrace MD5 hash the issue is related to
 * @return the ACRA bug occurrences listed in the description
 * @throws IssueParseException
 *             malformed issue description
 */
private List<ErrorOccurrence> parseAcraOccurrencesTable(final String pDescription, final String pStacktraceMD5)
        throws IssueParseException {

    final List<ErrorOccurrence> occur = new ArrayList<ErrorOccurrence>();

    // escape braces { and } to use strings in regexp
    final String header = IssueDescriptionUtils.getOccurrencesTableHeader();
    final String escHeader = Pattern.quote(header);

    // regexp to find occurrences tables
    final Pattern p = Pattern.compile(escHeader + IssueDescriptionUtils.EOL + "(?:" + OCCURR_LINE_PATTERN
            + IssueDescriptionUtils.EOL + "+)+", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    final Matcher m = p.matcher(pDescription);

    if (m.find()) {
        // regexp to find occurrences lines
        final Pattern pLine = Pattern.compile(OCCURR_LINE_PATTERN);
        final Matcher mLine = pLine.matcher(m.group());
        while (mLine.find()) {
            try {
                final StringTokenizer line = new StringTokenizer(mLine.group(), "|");
                final String acraReportId = line.nextToken();
                final String acraUserCrashDate = line.nextToken();
                final String acraRunFor = line.nextToken();
                final String acraAndroidVersion = line.nextToken();
                final String acraVersionCode = line.nextToken();
                final String acraVersionName = line.nextToken();
                final String acraDevice = line.nextToken();
                final ErrorOccurrence error = new ErrorOccurrence();
                error.setReportId(acraReportId);
                try {
                    error.setCrashDate(IssueDescriptionUtils.parseDate(acraUserCrashDate));
                    error.setRunFor(RunningTimeUtils.parseRunningTime(acraRunFor));
                } catch (final ParseException e) {
                    throw new IssueParseException(
                            "Unable to parse user crash date of ACRA report " + acraReportId, e);
                }
                error.setAndroidVersion(acraAndroidVersion);
                error.setVersionCode(acraVersionCode);
                error.setVersionName(acraVersionName);
                error.setDevice(acraDevice);
                occur.add(error);
            } catch (final NoSuchElementException e) {
                throw new IssueParseException("Unable to parse ACRA report line: " + mLine.group(), e);
            }
        }
    } else {
        throw new IssueParseException("No crash occurrence table found in the description");
    }

    if (m.find()) {
        throw new IssueParseException("More than 1 occurrence table found in the description");
    }

    if (CollectionUtils.isEmpty(occur)) {
        throw new IssueParseException("0 user crash occurrence found in the description");
    }

    return occur;
}

From source file:com.auto.solution.TestManager.TESTRAILTestManager.java

private HashMap<String, List<String>> getTestDataDetailsFromTestLinkToMapCollection(String testSuiteName)
        throws Exception {

    HashMap<String, List<String>> testDataCollection = new HashMap<String, List<String>>();

    ArrayList<Integer> testSuiteIds = new ArrayList<Integer>();
    int i = 0;/*from   www.  j  a va2  s  . co m*/

    try {

        TestSuite testSuite = testProject.getTestSuiteByName(testSuiteName);

        String descriptionOfTestSuite = testSuite.getDescription();

        String[] testDataContents = descriptionOfTestSuite.split("\r\n");

        for (String keyValuePairs : testDataContents) {

            if (keyValuePairs.contains("=")) {

                String[] key_values = keyValuePairs.split("=");

                String key = key_values[0].trim();

                String valuesAsString = key_values[1].trim();

                String[] values = valuesAsString.split(Pattern.quote("||"));

                List<String> listOfValues = new ArrayList<String>();

                for (String value : values) {

                    value = value.trim();

                    listOfValues.add(value);

                }

                testDataCollection.put(key, listOfValues);
            }

        }

        alsoStoreTestDataInGlobalVariables(testDataCollection);

    } catch (NullPointerException ne) {
        //No test data defined for test suite.
    } catch (TestLinkAPIException te) {
        String errMessage = ERROR_MESSAGES.ER_RETRIEVING_TESTCASE.getErrorMessage();
        errMessage = errMessage.replace("{PROJECT}", testProject.getName());
        errMessage = errMessage.replace("{TESTNAME}", testSuiteName);
        throw new Exception(errMessage);
    }
    return testDataCollection;
}

From source file:biomine.bmvis2.Vis.java

private static String assignTabTitle(String fileName) {
    String[] parts = fileName.split(Pattern.quote(System.getProperty("file.separator")));
    String baseName = parts[parts.length - 1];

    if (Vis.titleIndex == null)
        Vis.titleIndex = new HashMap<String, Integer>();

    if (!Vis.titleIndex.containsKey(baseName))
        Vis.titleIndex.put(baseName, 1);

    int index = Vis.titleIndex.get(baseName);

    if (index == 1) {
        Vis.titleIndex.put(baseName, index + 1);
        return baseName;
    }/*from  w w w  . j  av a 2  s .  com*/

    Vis.titleIndex.put(baseName, index + 1);
    return baseName + " [" + index + "]";
}

From source file:forge.util.FileUtil.java

public static List<Pair<String, String>> readNameUrlFile(String nameUrlFile) {
    Pattern lineSplitter = Pattern.compile(Pattern.quote(" "));
    Pattern replacer = Pattern.compile(Pattern.quote("%20"));

    List<Pair<String, String>> list = new ArrayList<Pair<String, String>>();

    for (String line : readFile(nameUrlFile)) {
        if (StringUtils.isBlank(line) || line.startsWith("#")) {
            continue;
        }//w ww.ja v a  2s. com

        String[] parts = lineSplitter.split(line, 2);
        if (2 == parts.length) {
            list.add(Pair.of(replacer.matcher(parts[0]).replaceAll(" "), parts[1]));
        } else {
            // figure out the filename from the URL
            Pattern pathSplitter = Pattern.compile(Pattern.quote("/"));
            String[] pathParts = pathSplitter.split(parts[0]);
            String last = pathParts[pathParts.length - 1];
            list.add(Pair.of(replacer.matcher(last).replaceAll(" "), parts[0]));
        }
    }

    return list;
}

From source file:fr.dudie.acrachilisync.tools.upgrade.IssueDescriptionReaderV1.java

/**
 * Extracts the bug stacktrace from the description.
 * //from  ww w.  ja va 2  s .  c  om
 * @param pDescription
 *            the issue description
 * @param pStacktraceMD5
 *            the stacktrace MD5 hash the issue is related to
 * @return the stacktrace
 * @throws IssueParseException
 *             malformed issue description
 */
private String parseStacktrace(final String pDescription, final String pStacktraceMD5)
        throws IssueParseException {

    String stacktrace = null;

    // escape braces { and } to use strings in regexp
    final String start = "<pre class=\"javastacktrace\">";
    final String qStart = Pattern.quote(start);
    final String end = "</pre>";
    final String qEnd = Pattern.quote(end);

    final Pattern p = Pattern.compile(qStart + "(.*)" + qEnd, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    final Matcher m = p.matcher(pDescription);

    if (m.find()) {
        stacktrace = m.group(1);
        // if a start tag or an end tag is found in the stacktrace, then there is a problem
        if (StringUtils.contains(stacktrace, start) || StringUtils.contains(stacktrace, end)) {
            throw new IssueParseException("Invalid stacktrace block");
        }
    } else {
        throw new IssueParseException("0 stacktrace block found in the description");
    }

    return stacktrace;
}

From source file:edu.kit.dama.util.ZipUtils.java

/**
 * Write a list of files into a ZipOutputStream. The provided base path is
 * used to keep the structure defined by pFileList within the zip file.<BR/>
 * Due to the fact, that we have only one single base path, all files within
 * 'pFileList' must have in the same base directory. Adding files from a
 * higher level will cause unexpected zip entries.
 *
 * @param pFileList The list of input files
 * @param pBasePath The base path the will be removed from all file paths
 * before creating a new zip entry/*from   w  ww .  j a  v a 2s. c  o  m*/
 * @param pZipOut The zip output stream
 * @throws IOException If something goes wrong, in most cases if there are
 * problems with reading the input files or writing into the output file
 */
private static void zip(File[] pFileList, String pBasePath, ZipOutputStream pZipOut) throws IOException {
    // Create a buffer for reading the files
    byte[] buf = new byte[1024];
    try {
        // Compress the files
        LOGGER.debug("Adding {} files to archive", pFileList.length);

        for (File pFileList1 : pFileList) {
            String entryName = pFileList1.getPath().replaceAll(Pattern.quote(pBasePath), "");
            if (entryName.startsWith(File.separator)) {
                entryName = entryName.substring(1);
            }

            if (pFileList1.isDirectory()) {
                LOGGER.debug("Adding directory entry");
                //add empty folders, too
                pZipOut.putNextEntry(new ZipEntry((entryName + File.separator).replaceAll("\\\\", "/")));
                pZipOut.closeEntry();
                File[] fileList = pFileList1.listFiles();
                if (fileList.length != 0) {
                    LOGGER.debug("Adding directory content recursively");
                    zip(fileList, pBasePath, pZipOut);
                } else {
                    LOGGER.debug("Skipping recursive call due to empty directory");
                }
                //should we close the entry here??
                //pZipOut.closeEntry();
            } else {
                LOGGER.debug("Adding file entry");
                try (final FileInputStream in = new FileInputStream(pFileList1)) {
                    // Add ZIP entry to output stream.
                    pZipOut.putNextEntry(new ZipEntry(entryName.replaceAll("\\\\", "/")));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        pZipOut.write(buf, 0, len);
                    }
                    // Complete the entry
                    LOGGER.debug("Closing file entry");
                    pZipOut.closeEntry();
                }
            }
        }
    } catch (IOException ioe) {
        LOGGER.error(
                "Aborting zip process due to an IOException caused by any zip stream (FileInput or ZipOutput)",
                ioe);
        throw ioe;
    } catch (RuntimeException e) {
        LOGGER.error("Aborting zip process due to an unexpected exception", e);
        throw new IOException("Unexpected exception during zip operation", e);
    }
}

From source file:de.joinout.criztovyl.tools.file.Path.java

/**
 * Creates the parent by specifying a child.
 * @param child the child as a {@link String}
 * @return a {@link Path}/*from ww  w .  ja  v  a 2 s .com*/
 */
public Path getParent(String child) {
    return new Path(getPath().replaceAll(Pattern.quote(child) + "$", ""), getSeparator());
}

From source file:de.codesourcery.jasm16.emulator.Breakpoint.java

private String substitutePlaceholders(final IEmulator emulator, String condition) {
    final String[] registers = new String[] { "pc", "ex", "sp", "a", "b", "c", "x", "y", "z", "i", "j" };

    String registerExpression = "";
    for (int i = 0; i < registers.length; i++) {
        final String reg = registers[i];
        registerExpression += reg;//from  www  .  j a  va2s. co  m
        if ((i + 1) < registers.length) {
            registerExpression += "|";
        }
    }
    final Pattern registerIndirectRegEx = Pattern.compile("\\[(" + registerExpression + ")\\]",
            Pattern.CASE_INSENSITIVE);

    final Pattern registerImmediateRegEx = Pattern.compile("(" + registerExpression + ")",
            Pattern.CASE_INSENSITIVE);

    final Pattern memoryIndirectRegEx = Pattern.compile("(\\[[ ]*(0x[0-9a-f]+)[ ]*\\])");

    final Pattern hexPattern = Pattern.compile("(0x[a-f0-9]+)", Pattern.CASE_INSENSITIVE);

    final StringBuilder result = new StringBuilder(condition);

    // first, replace all memory references with the memory's value
    // at the specified address

    final IPatternReplacer replacer1 = new IPatternReplacer() {

        @Override
        public String replace(Matcher matcher, String context) {
            final String hexString = matcher.group(2);
            final int address = (int) Misc.parseHexString(hexString);
            @SuppressWarnings("deprecation")
            final int decValue = emulator.getMemory().read(address);
            return context.replaceAll(Pattern.quote(matcher.group(1)), Integer.toString(decValue));
        }
    };

    substitutePatterns(result, memoryIndirectRegEx, replacer1);

    // second, substitute all hexadecimal values (0x1234) with their
    // decimal counterparse so we don't accidently replace a,b,c with their
    // register values      

    final IPatternReplacer replacer2 = new IPatternReplacer() {

        @Override
        public String replace(Matcher matcher, String context) {
            final String hexString = matcher.group(1);
            final long decValue = Misc.parseHexString(hexString);
            return context.replaceAll(Pattern.quote(hexString), Long.toString(decValue));
        }
    };

    substitutePatterns(result, hexPattern, replacer2);

    // third, replace all register indirect [ <REG> ] expressions with their respective
    // memory value

    final IPatternReplacer replacer3 = new IPatternReplacer() {

        @Override
        public String replace(Matcher matcher, String context) {
            final String register = matcher.group(1);
            final Register reg = Register.fromString(register);
            final int registerValue = emulator.getCPU().getRegisterValue(reg);
            @SuppressWarnings("deprecation")
            final int memoryValue = emulator.getMemory().read(registerValue);
            final String toReplace = Pattern.quote("[" + register + "]");
            return context.replaceAll(toReplace, Integer.toString(memoryValue));
        }
    };

    substitutePatterns(result, registerIndirectRegEx, replacer3);

    // fourth , replace all register immediate values with their respective
    // register values
    final IPatternReplacer replacer4 = new IPatternReplacer() {

        @Override
        public String replace(Matcher matcher, String context) {
            final String register = matcher.group(1);
            final Register reg = Register.fromString(register);
            final int decValue = emulator.getCPU().getRegisterValue(reg);
            final String toReplace = Pattern.quote(register);
            return context.replaceAll(toReplace, Integer.toString(decValue));
        }
    };

    substitutePatterns(result, registerImmediateRegEx, replacer4);

    return result.toString();
}

From source file:utils.Utils.java

public static String replaceVariables(String userdataRaw, Map<String, String> variables) {
    String userdata = userdataRaw;
    for (String variable : variables.keySet()) {
        log.debug("Replace " + variable + " with value " + variables.get(variable));
        userdata = userdata.replaceAll(Pattern.quote(variable), variables.get(variable));
        log.debug("Replaced userdata: " + userdata);
        //}/*from  w  ww  . j a v  a 2  s . c o  m*/
    }
    return userdata;
}