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:net.pandoragames.far.ui.SimpleFileNamePattern.java

/**
 * Validates the specified FileNamePattern for syntactically correctness.
 * @param pattern to be validated//from w  w  w. j  av a  2s  .  c  o m
 * @return true if pattern is ok
 */
public boolean validateFileNamePattern(FileNamePattern pattern) {
    if (pattern == null) {
        logger.warn("FileNamePattern object is null");
        return false;
    }
    if (pattern.getPattern() == null) {
        logger.warn("Pattern string is null");
        return false;
    }
    if (pattern.isRegex()) {
        try {
            return (null != Pattern.compile(pattern.getPattern()));
        } catch (PatternSyntaxException psx) {
            logger.info(psx.getMessage());
            return false;
        }
    } else {
        try {
            return (null != createPattern(pattern.getPattern(), true));
        } catch (PatternException px) {
            logger.info(px.getMessage());
            return false;
        }
    }
}

From source file:net.firejack.platform.core.validation.NotMatchProcessor.java

@Override
public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    List<ValidationMessage> messages = new ArrayList<ValidationMessage>();
    NotMatch notMatchAnnotation = readMethod.getAnnotation(NotMatch.class);
    if (notMatchAnnotation != null && StringUtils.isNotBlank(notMatchAnnotation.expression())) {
        Class<?> returnType = readMethod.getReturnType();
        if (returnType == String.class) {
            Pattern pattern = getCachedPatterns().get(notMatchAnnotation.expression());
            if (pattern == null) {
                try {
                    pattern = Pattern.compile(notMatchAnnotation.expression());
                    getCachedPatterns().put(notMatchAnnotation.expression(), pattern);
                } catch (PatternSyntaxException e) {
                    logger.error(e.getMessage(), e);
                    throw new ImproperValidationArgumentException(
                            "Pattern expression should have correct syntax.");
                }/*  www. ja  va2  s  .  com*/
            }
            if (value != null) {
                String sValue = (String) value;
                if (StringUtils.isNotBlank(sValue) && pattern.matcher(sValue).matches()) {
                    messages.add(new ValidationMessage(property, notMatchAnnotation.msgKey(),
                            notMatchAnnotation.parameterName()));
                }
            }
        }
    }

    if (notMatchAnnotation != null && !notMatchAnnotation.javaWords()) {
        Class<?> returnType = readMethod.getReturnType();
        if (returnType == String.class && StringUtils.isNotBlank((String) value)) {
            String s = (String) value;
            for (String word : words) {
                if (word.equals(s)) {
                    messages.add(new ValidationMessage(property, notMatchAnnotation.msgKey(), word));
                }
            }
        }
    }

    return messages;
}

From source file:com.medvision360.medrecord.server.archetype.ArchetypeListServerResource.java

@Override
public IDList listArchetypes() throws RecordException {
    String q = null;//from ww w .j av a  2 s  .c om
    try {
        try {
            Pattern pattern = null;
            q = getQueryValue("q");

            // Just to be quite clear about this: at this point q is a user-provided 'tainted' parameter.
            // It contains a regular expression. One of the many fun things you can do with regular expressions
            // is to write one which takes a glacial amount of time to process, and there is no good way to
            // predict that this may happen. So this is a great place to, for example, try to do a DOS attack
            // against the server.
            //
            // The assumption is that this API is deployed safely behind some kind of AAA similar to what
            // you would use to secure a web based SSH console or SQL admin console.

            if (q != null && !q.isEmpty()) {
                if (!q.startsWith("^")) {
                    q = "^.*?" + q;
                }
                if (!q.endsWith("$")) {
                    q += ".*?$";
                }
                try {
                    pattern = Pattern.compile(q);
                } catch (PatternSyntaxException e) {
                    throw new PatternException(e.getMessage());
                }
            }

            Iterable<ArchetypeID> idList = engine().getArchetypeStore().list();
            Iterable<String> stringList = Iterables.transform(idList, new Function<ArchetypeID, String>() {
                @Override
                public String apply(ArchetypeID input) {
                    if (input == null) {
                        return null;
                    }
                    return input.getValue();
                }
            });
            if (pattern != null) {
                final Pattern finalPattern = pattern;
                stringList = Iterables.filter(stringList, new Predicate<String>() {
                    @Override
                    public boolean apply(String input) {
                        return finalPattern.matcher(input).matches();
                    }
                });
            }

            IDList result = new IDList();
            result.setIds(Lists.newArrayList(stringList));
            Events.append("LIST", q == null ? "all" : q, "ARCHETYPE_LIST", "listArchetypes",
                    String.format("Listed archetypes%s", q == null ? "" : " matching " + q));
            return result;
        } catch (IOException e) {
            throw new IORecordException(e.getMessage(), e);
        }
    } catch (RecordException | RuntimeException e) {
        Events.append("ERROR", q == null ? "all" : q, "ARCHETYPE_LIST", "listArchetypesFailure", String
                .format("Failure to list archetypes%s: %s", q == null ? "" : " matching " + q, e.getMessage()));
        throw e;
    }
}

From source file:jenkins.plugins.publish_over.ParamPublish.java

public PubSelector createSelector(final BPBuildInfo buildInfo) {
    if (Util.fixEmptyAndTrim(parameterName) == null)
        return SelectAllPubSelector.SELECT_ALL;
    final String regexp = buildInfo.getCurrentBuildEnv().getEnvVars().get(parameterName);
    if (regexp == null)
        throw new BapPublisherException(Messages.exception_paramPublish_noParameter(parameterName));
    try {//from ww  w  .  j  a  v a2 s .  c  o  m
        final Pattern pattern = Pattern.compile(regexp);
        return new Selector(buildInfo, pattern);
    } catch (PatternSyntaxException pse) {
        throw new BapPublisherException(
                Messages.exception_paramPublish_badPattern(parameterName, regexp, pse.getMessage()), pse);
    }
}

From source file:net.sf.zekr.engine.search.tanzil.ZeroHighlighter.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private List filterBucket(List intermediateResult, String pattern, boolean exclude, boolean firstTime,
        PatternEnricher enricher) throws SearchException {
    try {/* w w w.ja  va  2 s . c o m*/
        List res = new ArrayList();
        Pattern regex = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        for (int i = 0; i < intermediateResult.size(); i++) {
            Matcher matcher;
            String line;
            IQuranLocation loc;
            if (firstTime) {
                loc = (IQuranLocation) intermediateResult.get(i);
                line = ' ' + quranText.get(loc) + ' ';
            } else {
                SearchResultItem sri = (SearchResultItem) intermediateResult.get(i);
                loc = sri.location;
                line = sri.text;
            }
            // matcher = regex.matcher(enricher.enrich(line));
            matcher = regex.matcher(line);
            if (matcher.find() ^ exclude) {
                if (firstTime) {
                    res.add(new SearchResultItem(line, loc));
                } else {
                    res.add(intermediateResult.get(i));
                }
            }
        }
        return res;
    } catch (PatternSyntaxException pse) {
        logger.implicitLog(pse);
        throw new SearchException(pse.getMessage());
    }
}

From source file:org.alfresco.util.registry.NamedObjectRegistry.java

/**
 * Optionally set a pattern to which all object names must conform
 * @param namePattern   a regular expression
 *//*  w  ww.j  av  a  2  s.c  om*/
public void setNamePattern(String namePattern) {
    writeLock.lock();
    try {
        this.namePattern = Pattern.compile(namePattern);
    } catch (PatternSyntaxException e) {
        throw new AlfrescoRuntimeException(
                "Regular expression compilation failed for property 'namePrefix': " + e.getMessage(), e);
    } finally {
        writeLock.unlock();
    }
}

From source file:jp.ikedam.jenkins.plugins.jobcopy_builder.ReplaceRegExpOperation.java

/**
 * Returns modified XML Document of the job configuration.
 *
 * Replace the strings in the job configuration: only applied to strings in text nodes, so the XML structure is never destroyed.
 *
 * @param doc/*from w  w  w.  j  a  v a2  s.c o  m*/
 *            XML Document of the job to be copied (job/NAME/config.xml)
 * @param env
 *            Variables defined in the build.
 * @param logger
 *            The output stream to log.
 * @return modified XML Document. Return null if an error occurs.
 * @see jp.ikedam.jenkins.plugins.jobcopy_builder.AbstractXmlJobcopyOperation#perform(org.w3c.dom.Document, hudson.EnvVars, java.io.PrintStream)
 */
@Override
public Document perform(final Document doc, final EnvVars env, final PrintStream logger) {
    final String fromStr = getFromStr();
    String toStr = getToStr();

    if (StringUtils.isEmpty(fromStr)) {
        logger.println("From String is empty");
        return null;
    }
    if (toStr == null) {
        toStr = "";
    }
    final String expandedFromStr = isExpandFromStr() ? env.expand(fromStr) : maskSpecialChars(fromStr);

    Pattern pattern;
    try {
        pattern = Pattern.compile(expandedFromStr);
    } catch (final PatternSyntaxException e) {
        logger.println("Error on regular expression: " + e.getMessage());
        return null;
    }

    String expandedToStr = isExpandToStr() ? env.expand(toStr) : maskSpecialChars(toStr);
    if (StringUtils.isEmpty(expandedFromStr)) {
        logger.println("From String got to be empty");
        return null;
    }
    if (expandedToStr == null) {
        expandedToStr = "";
    }

    logger.print("Replacing with RegExp: " + expandedFromStr + " -> " + expandedToStr);
    try {
        // Retrieve all text nodes.
        final NodeList textNodeList = getNodeList(doc, "//text()");

        // Perform replacing to all text nodes.
        // NodeList does not implement Collection, and foreach is not usable.
        for (int i = 0; i < textNodeList.getLength(); ++i) {
            final Node node = textNodeList.item(i);
            final String nodeValue = node.getNodeValue();
            String newNodeValue = nodeValue;
            final Matcher matcher = pattern.matcher(nodeValue);
            // check all occurance
            while (matcher.find()) {
                newNodeValue = matcher.replaceAll(expandedToStr);
            }
            node.setNodeValue(newNodeValue);
        }
        logger.println("");

        return doc;
    } catch (final Exception e) {
        logger.print("Error occured in XML operation");
        e.printStackTrace(logger);
        return null;
    }
}

From source file:com.ning.maven.plugins.duplicatefinder.ClasspathDescriptor.java

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

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

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

/** Handle a SolrException.
* These exceptions are mainly Http errors having to do with actual responses from Solr.
* If this method doesn't throw an exception, it means that the exception should be interpreted
* as meaning that the document or action is illegal and should not be repeated.
*//*from w  w  w  . j  ava 2  s  . c om*/
protected static void handleSolrException(SolrException e, String context)
        throws ManifoldCFException, ServiceInterruption {
    int code = e.code();
    if (code == 0) {
        try {
            // Solrj doesn't always set the code properly.  If it doesn't, we have to parse it out of the exception string.  Ugh.
            Pattern p = Pattern.compile("non ok status:([0-9]*),");
            Matcher m = p.matcher(e.getMessage());
            if (m.find())
                code = Integer.parseInt(m.group(1));
        } catch (PatternSyntaxException e2) {
            throw new ManifoldCFException("Unexpected error: " + e2.getMessage());
        } catch (NumberFormatException e2) {
            throw new ManifoldCFException("Unexpected error: " + e2.getMessage());
        }
    }

    // Use the exception text to determine the proper result.
    if (code == 500 && e.getMessage().indexOf("org.apache.tika.exception.TikaException") != -1)
        // Can't process the document, so don't keep trying.
        return;

    // If the code is in the 400 range, the document will never be accepted, so indicate that.
    if (code >= 400 && code < 500)
        return;

    // The only other kind of return code we know how to handle is 50x.
    // For these, we should retry for a while.
    if (code == 500) {
        long currentTime = System.currentTimeMillis();

        // Log the error
        String message = "Solr exception during " + context + " (" + e.code() + "): " + e.getMessage();
        Logging.ingest.warn(message, e);
        throw new ServiceInterruption(message, e, currentTime + interruptionRetryTime,
                currentTime + 2L * 60L * 60000L, -1, true);
    }

    // Unknown code: end the job.
    throw new ManifoldCFException(
            "Unhandled Solr exception during " + context + " (" + e.code() + "): " + e.getMessage());
}

From source file:esg.node.core.AbstractDataNodeManager.java

public Properties getMatchingProperties(String regex) {
    log.trace("getting matching properties for [" + regex + "]");
    Properties matchProps = null;
    if ((matchProps = propCache.get(regex)) != null) {
        return matchProps;
    }/*from   ww w  . j  a  v  a 2s  . com*/
    matchProps = new Properties();
    String key = null;
    for (Enumeration keys = props.propertyNames(); keys.hasMoreElements();) {
        key = (String) keys.nextElement();
        //log.trace("inspecting: "+key);
        try {
            if (key.matches(regex)) {
                //log.trace("matched: adding...");
                matchProps.put(key, props.getProperty(key));
            }
        } catch (PatternSyntaxException ex) {
            log.error(ex.getMessage(), ex);
            break;
        }
    }
    propCache.put(regex, matchProps);
    log.trace("[" + regex + "] => (" + matchProps.size() + " entries)");
    log.trace("propCache size = " + propCache.size());
    return matchProps;
}