Example usage for java.util.regex PatternSyntaxException getMessage

List of usage examples for java.util.regex PatternSyntaxException getMessage

Introduction

In this page you can find the example usage for java.util.regex PatternSyntaxException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.

Usage

From source file:org.apache.metron.parsers.regex.RegularExpressionsParser.java

/**
 * This method is called during the parser initialization. It parses the parser
 * configuration and configures the parser accordingly. It then initializes
 * instance variables./*from   ww w .  j  a v a  2s . c om*/
 *
 * @param parserConfig ParserConfig(Map<String, Object>) supplied to the sensor.
 * @see org.apache.metron.parsers.interfaces.Configurable#configure(java.util.Map)<br>
 *      <br>
 */
// @formatter:on
@Override
public void configure(Map<String, Object> parserConfig) {
    setParserConfig(parserConfig);
    setFields((List<Map<String, Object>>) getParserConfig().get(ParserConfigConstants.FIELDS.getName()));
    String recordTypeRegex = (String) getParserConfig().get(ParserConfigConstants.RECORD_TYPE_REGEX.getName());

    if (StringUtils.isBlank(recordTypeRegex)) {
        LOG.error("Invalid config :recordTypeRegex is missing in parserConfig");
        throw new IllegalStateException("Invalid config :recordTypeRegex is missing in parserConfig");
    }

    setRecordTypePattern(recordTypeRegex);
    recordTypePatternNamedGroups.addAll(getNamedGroups(recordTypeRegex));
    List<Map<String, Object>> fields = (List<Map<String, Object>>) getParserConfig()
            .get(ParserConfigConstants.FIELDS.getName());

    try {
        configureRecordTypePatterns(fields);
        configureMessageHeaderPattern();
    } catch (PatternSyntaxException e) {
        LOG.error("Invalid config : {} ", e.getMessage());
        throw new IllegalStateException("Invalid config : " + e.getMessage());
    }

    validateConfig();
}

From source file:org.apache.nutch.indexer.replace.ReplaceIndexer.java

/**
 * Parse the property value into a set of maps that store a list of
 * replacements by field for each host and url configured into the property.
 * /*from  ww w  .j a v  a 2 s  . c o m*/
 * @param propertyValue
 */
private void parseConf(String propertyValue) {
    if (propertyValue == null || propertyValue.trim().length() == 0) {
        return;
    }

    // At the start, all replacements apply globally to every host.
    Pattern hostPattern = Pattern.compile(".*");
    Pattern urlPattern = null;

    // Split the property into lines
    Matcher lineMatcher = LINE_SPLIT.matcher(propertyValue);
    while (lineMatcher.find()) {
        String line = lineMatcher.group();
        if (line != null && line.length() > 0) {

            // Split the line into field and value
            Matcher nameValueMatcher = NAME_VALUE_SPLIT.matcher(line.trim());
            if (nameValueMatcher.find()) {
                String fieldName = nameValueMatcher.group(1).trim();
                String value = nameValueMatcher.group(2);
                if (fieldName != null && value != null) {
                    // Check if the field name is one of our special cases.
                    if (HOSTMATCH.equals(fieldName)) {
                        urlPattern = null;
                        try {
                            hostPattern = Pattern.compile(value);
                        } catch (PatternSyntaxException pse) {
                            LOG.error("hostmatch pattern " + value + " does not compile: " + pse.getMessage());
                            // Deactivate this invalid match set by making it match no host.
                            hostPattern = Pattern.compile("willnotmatchanyhost");
                        }
                    } else if (URLMATCH.equals(fieldName)) {
                        try {
                            urlPattern = Pattern.compile(value);
                        } catch (PatternSyntaxException pse) {
                            LOG.error("urlmatch pattern " + value + " does not compile: " + pse.getMessage());
                            // Deactivate this invalid match set by making it match no url.
                            urlPattern = Pattern.compile("willnotmatchanyurl");
                        }
                    } else if (value.length() > 3) {
                        String toFieldName = fieldName;
                        // If the fieldname has a colon, this indicates a different target
                        // field.
                        if (fieldName.indexOf(':') > 0) {
                            toFieldName = fieldName.substring(fieldName.indexOf(':') + 1);
                            fieldName = fieldName.substring(0, fieldName.indexOf(':'));
                        }
                        String sep = value.substring(0, 1);

                        // Divide the value into pattern / replacement / flags.
                        value = value.substring(1);
                        if (!value.contains(sep)) {
                            LOG.error("Pattern '" + line + "', not parseable.  Missing separator " + sep);
                            continue;
                        }
                        String pattern = value.substring(0, value.indexOf(sep));
                        value = value.substring(pattern.length() + 1);
                        String replacement = value;
                        if (value.contains(sep)) {
                            replacement = value.substring(0, value.indexOf(sep));
                        }
                        int flags = 0;
                        if (value.length() > replacement.length() + 1) {
                            value = value.substring(replacement.length() + 1).trim();
                            try {
                                flags = Integer.parseInt(value);
                            } catch (NumberFormatException e) {
                                LOG.error("Pattern " + line + ", has invalid flags component");
                                continue;
                            }
                        }
                        Integer iFlags = (flags > 0) ? new Integer(flags) : null;

                        // Make a FieldReplacer out of these params.
                        FieldReplacer fr = new FieldReplacer(fieldName, toFieldName, pattern, replacement,
                                iFlags);

                        // Add this field replacer to the list for this host or URL.
                        if (urlPattern != null) {
                            List<FieldReplacer> lfp = FIELDREPLACERS_BY_URL.get(urlPattern);
                            if (lfp == null) {
                                lfp = new ArrayList<FieldReplacer>();
                            }
                            lfp.add(fr);
                            FIELDREPLACERS_BY_URL.put(urlPattern, lfp);
                        } else {
                            List<FieldReplacer> lfp = FIELDREPLACERS_BY_HOST.get(hostPattern);
                            if (lfp == null) {
                                lfp = new ArrayList<FieldReplacer>();
                            }
                            lfp.add(fr);
                            FIELDREPLACERS_BY_HOST.put(hostPattern, lfp);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.roller.weblogger.business.plugins.entry.TopicTagPlugin.java

/**
 * Initialize the plugin instance.   This sets up the configurable properties and default topic site.
 * /*from   w  ww  . j  a va 2  s.  c o  m*/
 * @param rreq Plugins may need to access RollerRequest.
 * @param ctx  Plugins may place objects into the Velocity Context.
 * @see PagWeblogEntryPluginit(org.apache.roller.weblogger.presentation.RollerRequest, org.apache.velocity.context.Context)
 */
public void init(Weblog website) throws WebloggerException {
    if (mLogger.isDebugEnabled()) {
        mLogger.debug("TopicTagPlugin v. " + version);
    }

    // Initialize property settings
    initializeProperties();

    // Build map of the user's bookmarks
    userBookmarks = buildBookmarkMap(website);

    // Determine default topic site from bookmark if present
    WeblogBookmark defaultTopicBookmark = (WeblogBookmark) userBookmarks.get(defaultTopicBookmarkName);
    if (defaultTopicBookmark != null)
        defaultTopicSite = defaultTopicBookmark.getUrl();

    // Append / to defaultTopicSite if it doesn't have it
    if (!defaultTopicSite.endsWith("/")) {
        defaultTopicSite += "/";
    }

    // Compile patterns and make sure they have the correct number of matching groups in them.
    try {
        tagPatternWithBookmark = Pattern.compile(tagRegexWithBookmark);
    } catch (PatternSyntaxException e) {
        throw new WebloggerException("Invalid regular expression for topic tags with bookmark '"
                + tagRegexWithBookmark + "': " + e.getMessage());
    }
    int groupCount = tagPatternWithBookmark.matcher("").groupCount();
    if (groupCount != 2) {
        throw new WebloggerException("Regular expression for topic tags with bookmark '" + tagRegexWithBookmark
                + "' contains wrong number of capture groups.  Must have exactly 2.  Contains " + groupCount);
    }

    try {
        tagPatternWithoutBookmark = Pattern.compile(tagRegexWithoutBookmark);
    } catch (PatternSyntaxException e) {
        throw new WebloggerException("Invalid regular expression for topic tags without bookmark '"
                + tagRegexWithoutBookmark + "': " + e.getMessage());
    }
    groupCount = tagPatternWithoutBookmark.matcher("").groupCount();
    if (groupCount != 1) {
        throw new WebloggerException("Regular expression for topic tags without bookmark '"
                + tagRegexWithoutBookmark
                + "' contains wrong number of capture groups.  Must have exactly 1.  Contains " + groupCount);
    }

    // Create link format from format string
    setLinkFormat(new MessageFormat(linkFormatString));
}

From source file:org.bsc.maven.plugin.findclass.ClasspathDescriptor.java

public void setIgnoredResources(final String[] ignoredResources) throws MojoExecutionException {
    if (ignoredResources != null) {
        ignoredResourcesPatterns = new Pattern[ignoredResources.length];

        try {//from w  w  w .j  a v  a2s.  c o m
            for (int i = 0; i < ignoredResources.length; i++) {
                ignoredResourcesPatterns[i] = Pattern.compile(ignoredResources[i].toUpperCase());
            }
        } catch (final PatternSyntaxException pse) {
            throw new MojoExecutionException("Error compiling resourceIgnore pattern: " + pse.getMessage());
        }
    }
}

From source file:org.cerberus.serviceEngine.impl.SeleniumService.java

@Override
public MessageEvent doSeleniumActionSelect(Selenium selenium, String html, String property) {
    MessageEvent message;//from  w ww . j a  v a  2  s.  c o m
    String identifier;
    String value = "";

    try {
        if (!StringUtil.isNull(html) && !StringUtil.isNull(property)) {

            String[] strings = property.split("=");
            if (strings.length == 1) {
                identifier = "value";
                value = strings[0];
            } else {
                identifier = strings[0];
                value = strings[1];
            }

            Select select;
            try {
                select = new Select(this.getSeleniumElement(selenium, html, true));
            } catch (NoSuchElementException exception) {
                message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT_NO_SUCH_ELEMENT);
                message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
                MyLogger.log(SeleniumService.class.getName(), Level.ERROR, exception.toString());
                return message;
            }
            if (identifier.equalsIgnoreCase("value")) {
                select.selectByValue(value);
                message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_SELECT);
                message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
                message.setDescription(message.getDescription().replaceAll("%DATA%", property));
                return message;
            } else if (identifier.equalsIgnoreCase("label")) {
                select.selectByVisibleText(value);
                message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_SELECT);
                message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
                message.setDescription(message.getDescription().replaceAll("%DATA%", property));
                return message;
            } else if (identifier.equalsIgnoreCase("index") && StringUtil.isNumeric(value)) {
                select.selectByIndex(Integer.parseInt(value));
                message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_SELECT);
                message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
                message.setDescription(message.getDescription().replaceAll("%DATA%", property));
                return message;
            } else if (identifier.equalsIgnoreCase("regexValue") || identifier.equalsIgnoreCase("regexIndex")
                    || identifier.equalsIgnoreCase("regexLabel")) {
                java.util.List<WebElement> list = select.getOptions();

                if (identifier.equalsIgnoreCase("regexValue")) {
                    for (WebElement option : list) {
                        String optionValue = option.getAttribute("value");
                        Pattern pattern = Pattern.compile(value);
                        Matcher matcher = pattern.matcher(optionValue);

                        if (matcher.find()) {
                            select.selectByValue(optionValue);
                            message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_SELECT);
                            message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
                            message.setDescription(message.getDescription().replaceAll("%DATA%", property));
                            return message;
                        }
                    }
                } else if (identifier.equalsIgnoreCase("regexLabel")) {
                    for (WebElement option : list) {
                        String optionLabel = option.getText();
                        Pattern pattern = Pattern.compile(value);
                        Matcher matcher = pattern.matcher(optionLabel);

                        if (matcher.find()) {
                            select.selectByVisibleText(optionLabel);
                            message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_SELECT);
                            message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
                            message.setDescription(message.getDescription().replaceAll("%DATA%", property));
                            return message;
                        }
                    }
                } else if (identifier.equalsIgnoreCase("regexIndex") && StringUtil.isNumeric(value)) {
                    for (WebElement option : list) {
                        Integer id = 0;
                        Pattern pattern = Pattern.compile(value);
                        Matcher matcher = pattern.matcher(id.toString());

                        if (matcher.find()) {
                            select.selectByIndex(Integer.parseInt(value));
                            message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_SELECT);
                            message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
                            message.setDescription(message.getDescription().replaceAll("%DATA%", property));
                            return message;
                        }
                        id++;
                    }
                }
            } else {
                message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT_NO_IDENTIFIER);
                message.setDescription(message.getDescription().replaceAll("%IDENTIFIER%", html));
                return message;
            }
        }
    } catch (NoSuchElementException exception) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT_NO_SUCH_VALUE);
        message.setDescription(message.getDescription().replaceAll("%ELEMENT%", html));
        message.setDescription(message.getDescription().replaceAll("%DATA%", property));
        return message;
    } catch (WebDriverException exception) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELENIUM_CONNECTIVITY);
        MyLogger.log(SeleniumService.class.getName(), Level.FATAL, exception.toString());
        return message;
    } catch (PatternSyntaxException e) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT_REGEX_INVALIDPATERN);
        message.setDescription(message.getDescription().replaceAll("%PATERN%", value));
        message.setDescription(message.getDescription().replaceAll("%ERROR%", e.getMessage()));
        return message;
    }
    return new MessageEvent(MessageEventEnum.ACTION_FAILED_SELECT);
}

From source file:org.codehaus.groovy.grails.web.mapping.RegexUrlMapping.java

/**
 * Converts a Grails URL provides via the UrlMappingData interface to a regular expression.
 *
 * @param url The URL to convert/*from w  w w.ja  v  a2s . c om*/
 * @return A regex Pattern objet
 */
protected Pattern convertToRegex(String url) {
    Pattern regex;
    String pattern = null;
    try {
        // Escape any characters that have special meaning in regular expressions,
        // such as '.' and '+'.
        pattern = url.replace(".", "\\.");
        pattern = pattern.replace("+", "\\+");

        int lastSlash = pattern.lastIndexOf('/');

        String urlRoot = lastSlash > -1 ? pattern.substring(0, lastSlash) : pattern;
        String urlEnd = lastSlash > -1 ? pattern.substring(lastSlash, pattern.length()) : "";

        // Now replace "*" with "[^/]" and "**" with ".*".
        pattern = "^"
                + urlRoot.replace("(\\.(*))", "\\.?([^/]+)?").replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+$2")
                        .replaceAll("([^\\*])\\*$", "$1[^/]+").replaceAll("\\*\\*", ".*");

        pattern += urlEnd.replace("(\\.(*))", "\\.?([^/]+)?").replaceAll("([^\\*])\\*([^\\*])", "$1[^/\\.]+$2")
                .replaceAll("([^\\*])\\*$", "$1[^/\\.]+").replaceAll("\\*\\*", ".*");

        pattern += "/??$";
        regex = Pattern.compile(pattern);
    } catch (PatternSyntaxException pse) {
        throw new UrlMappingException("Error evaluating mapping for pattern [" + pattern
                + "] from Grails URL mappings: " + pse.getMessage(), pse);
    }

    return regex;
}

From source file:org.dspace.app.util.DCInput.java

public boolean validate(String value) {
    if (StringUtils.isNotBlank(value)) {
        try {/*from   w  ww  . j  av a 2s  . c  om*/
            if (StringUtils.isNotBlank(regex)) {
                Pattern pattern = Pattern.compile(regex);
                if (!pattern.matcher(value).matches()) {
                    return false;
                }
            }
        } catch (PatternSyntaxException ex) {
            log.error("Regex validation failed!", ex.getMessage());
        }

    }

    return true;
}

From source file:org.freeplane.view.swing.features.time.mindmapmode.nodelist.NodeList.java

private void replace(final HolderAccessor holderAccessor) {
    final String searchString = (String) mFilterTextSearchField.getSelectedItem();
    if (searchString == null)
        return;/*w  w w  . j a  v a2 s. co  m*/
    final String replaceString = (String) mFilterTextReplaceField.getSelectedItem();
    Pattern p;
    try {
        p = Pattern.compile(useRegexInFind.isSelected() ? searchString : Pattern.quote(searchString),
                matchCase.isSelected() ? 0 : Pattern.CASE_INSENSITIVE);
    } catch (final PatternSyntaxException e) {
        UITools.errorMessage(TextUtils.format("wrong_regexp", searchString, e.getMessage()));
        return;
    }
    final String replacement = replaceString == null ? "" : replaceString;
    final int length = holderAccessor.getLength();
    for (int i = 0; i < length; i++) {
        TextHolder[] textHolders = holderAccessor.getNodeHoldersAt(i);
        for (final TextHolder textHolder : textHolders) {
            final String text = textHolder.getText();
            final String replaceResult;
            final String literalReplacement = useRegexInReplace.isSelected() ? replacement
                    : Matcher.quoteReplacement(replacement);
            try {
                if (HtmlUtils.isHtmlNode(text)) {
                    replaceResult = NodeList.replace(p, text, literalReplacement);
                } else {
                    replaceResult = p.matcher(text).replaceAll(literalReplacement);
                }
            } catch (Exception e) {
                UITools.errorMessage(TextUtils.format("wrong_regexp", replacement, e.getMessage()));
                return;
            }
            if (!StringUtils.equals(text, replaceResult)) {
                holderAccessor.changeString(textHolder, replaceResult);
            }
        }
    }
    tableModel.fireTableDataChanged();
    mFlatNodeTableFilterModel.resetFilter();
    mFilterTextSearchField.insertItemAt(mFilterTextSearchField.getSelectedItem(), 0);
    mFilterTextReplaceField.insertItemAt(mFilterTextReplaceField.getSelectedItem(), 0);
    mFilterTextSearchField.setSelectedItem("");
}

From source file:org.freeplane.view.swing.features.time.mindmapmode.NodeList.java

private void replace(final IReplaceInputInformation info) {
    final String searchString = (String) mFilterTextSearchField.getSelectedItem();
    if (searchString == null)
        return;/*from   w  w  w.  j  a  v  a 2s  .  com*/
    final String replaceString = (String) mFilterTextReplaceField.getSelectedItem();
    Pattern p;
    try {
        p = Pattern.compile(useRegexInFind.isSelected() ? searchString : Pattern.quote(searchString),
                matchCase.isSelected() ? 0 : Pattern.CASE_INSENSITIVE);
    } catch (final PatternSyntaxException e) {
        UITools.errorMessage(TextUtils.format("wrong_regexp", searchString, e.getMessage()));
        return;
    }
    final String replacement = replaceString == null ? "" : replaceString;
    final int length = info.getLength();
    for (int i = 0; i < length; i++) {
        final NodeHolder nodeHolder = info.getNodeHolderAt(i);
        final String text = nodeHolder.node.getText();
        final String replaceResult;
        final String literalReplacement = useRegexInReplace.isSelected() ? replacement
                : Matcher.quoteReplacement(replacement);
        try {
            if (HtmlUtils.isHtmlNode(text)) {
                replaceResult = NodeList.replace(p, text, literalReplacement);
            } else {
                replaceResult = p.matcher(text).replaceAll(literalReplacement);
            }
        } catch (Exception e) {
            UITools.errorMessage(TextUtils.format("wrong_regexp", replacement, e.getMessage()));
            return;
        }
        if (!StringUtils.equals(text, replaceResult)) {
            info.changeString(nodeHolder, replaceResult);
        }
    }
    timeTableModel.fireTableDataChanged();
    mFlatNodeTableFilterModel.resetFilter();
    mFilterTextSearchField.insertItemAt(mFilterTextSearchField.getSelectedItem(), 0);
    mFilterTextReplaceField.insertItemAt(mFilterTextReplaceField.getSelectedItem(), 0);
    mFilterTextSearchField.setSelectedItem("");
}

From source file:org.grails.web.mapping.RegexUrlMapping.java

/**
 * Converts a Grails URL provides via the UrlMappingData interface to a regular expression.
 *
 * @param url The URL to convert//from  w  w  w.  j a  v  a  2s. co m
 * @return A regex Pattern objet
 */
protected Pattern convertToRegex(String url) {
    Pattern regex;
    String pattern = null;
    try {
        // Escape any characters that have special meaning in regular expressions,
        // such as '.' and '+'.
        pattern = url.replace(".", "\\.");
        pattern = pattern.replace("+", "\\+");

        int lastSlash = pattern.lastIndexOf('/');

        String urlRoot = lastSlash > -1 ? pattern.substring(0, lastSlash) : pattern;
        String urlEnd = lastSlash > -1 ? pattern.substring(lastSlash, pattern.length()) : "";

        // Now replace "*" with "[^/]" and "**" with ".*".
        pattern = "^"
                + urlRoot.replace("(\\.(*))", "\\.?([^/]+)?").replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+$2")
                        .replaceAll("([^\\*])\\*$", "$1[^/]+").replaceAll("\\*\\*", ".*");

        if ("/(*)(\\.(*))".equals(urlEnd)) {
            // shortcut this common special case which will
            // happen any time a URL mapping ends with a pattern like
            // /$someVariable(.$someExtension)
            pattern += "/([^/]+)\\.([^/.]+)?";
        } else {
            pattern += urlEnd.replace("(\\.(*))", "\\.?([^/]+)?").replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+$2")
                    .replaceAll("([^\\*])\\*$", "$1[^/]+").replaceAll("\\*\\*", ".*")
                    .replaceAll("\\(\\[\\^\\/\\]\\+\\)\\\\\\.", "([^/.]+)\\\\.")
                    .replaceAll("\\(\\[\\^\\/\\]\\+\\)\\?\\\\\\.", "([^/.]+)\\?\\\\.");
        }
        pattern += "/??$";
        regex = Pattern.compile(pattern);
    } catch (PatternSyntaxException pse) {
        throw new UrlMappingException("Error evaluating mapping for pattern [" + pattern
                + "] from Grails URL mappings: " + pse.getMessage(), pse);
    }

    return regex;
}