Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RegEx Validation Using Java Patterns (perf) #176

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@

package com.github.fge.jsonschema.keyword.validator.common;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.processing.Processor;
Expand All @@ -31,13 +34,15 @@
/**
* Keyword validator for {@code pattern}
*
* @see RhinoHelper
*/
public final class PatternValidator
extends AbstractKeywordValidator
{
private HashMap<String, Pattern> _patterns;

public PatternValidator(final JsonNode digest)
{
_patterns = new HashMap<String, Pattern>();
super("pattern");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

super should be the first statement in the constructor, otherwise, compilation fail with

call to super must be first statement in constructor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

}

Expand All @@ -50,7 +55,11 @@ public void validate(final Processor<FullData, FullData> processor,
final String regex = data.getSchema().getNode().get(keyword)
.textValue();
final String value = data.getInstance().getNode().textValue();
if (!RhinoHelper.regMatch(regex, value))

Pattern pattern = getPattern(regex);
Matcher matches = pattern.matcher(value);

if (!matches.find())
report.error(newMsg(data, bundle, "err.common.pattern.noMatch")
.putArgument("regex", regex).putArgument("string", value));
}
Expand All @@ -60,4 +69,15 @@ public String toString()
{
return keyword;
}

private Pattern getPattern(String regex)
{
// If there is not any existing compiled pattern, create one now!
if (!_patterns.containsKey(regex))
{
_patterns.put(regex, Pattern.compile(regex));
}

return _patterns.get(regex);
}
}