下面列出了java.util.regex.PatternSyntaxException#getMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public VersionOptBuilder withSeparatorExpression( String expression )
{
if ( StringUtils.isEmpty( expression ) )
{
throw new IllegalArgumentException( "Separator expression may not be null or empty" );
}
this.item.separatorExpression = expression;
try
{
updateVersionSegments( );
}
catch ( PatternSyntaxException e )
{
throw new IllegalArgumentException( "Bad separator expression " + expression + ": " + e.getMessage( ), e );
}
return this;
}
private Attribute[] getAttributesArrayFromRegex(Attributes attributes, String regex) throws OperatorException {
Pattern pattern = null;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new UserError(this, 206, regex, e.getMessage());
}
List<Attribute> attributeList = new LinkedList<>();
Iterator<Attribute> i = attributes.allAttributes();
while (i.hasNext()) {
Attribute attribute = i.next();
Matcher matcher = pattern.matcher(attribute.getName());
if (matcher.matches()) {
attributeList.add(attribute);
}
}
Attribute[] attributesArray = new Attribute[attributeList.size()];
attributesArray = attributeList.toArray(attributesArray);
return attributesArray;
}
private Attribute[] getMatchingAttributes(Attributes attributes, String regex) throws OperatorException {
Pattern pattern = null;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new UserError(this, 206, regex, e.getMessage());
}
List<Attribute> attributeList = new LinkedList<>();
Iterator<Attribute> iterator = attributes.allAttributes();
while (iterator.hasNext()) {
Attribute attribute = iterator.next();
if (pattern.matcher(attribute.getName()).matches()) {
attributeList.add(attribute);
}
}
// building array of attributes for faster access.
Attribute[] attributesArray = new Attribute[attributeList.size()];
attributesArray = attributeList.toArray(attributesArray);
return attributesArray;
}
private static String fixUnicodeScriptPattern(String rawPattern) {
for (int i = 0; i < UNICODE_SCRIPT_FIX_COUNTER; i++) {
try {
Pattern.compile(rawPattern);
return rawPattern;
} catch (final PatternSyntaxException ex) {
LOG.debug("Invalid regex pattern syntax in: {}", rawPattern, ex);
final String msg = ex.getMessage();
if (msg.startsWith("Unknown character script name")
|| msg.startsWith("Unknown character property name")) {
rawPattern = fixUnknownScripts(msg, rawPattern);
} else {
return rawPattern;
}
}
}
LOG.warn("Regex pattern could not be fixed: {}", rawPattern);
return rawPattern;
}
@Override
public NamespaceOptBuilder withSeparatorExpression( String expression )
{
if ( StringUtils.isEmpty( expression ) )
{
throw new IllegalArgumentException( "Separator expression may not be null or empty" );
}
this.item.separatorExpression = expression;
try
{
setNamespacePath( this.item.namespace );
}
catch ( PatternSyntaxException e )
{
throw new IllegalArgumentException( "Bad pattern syntax separator expression " + expression + ": " + e.getMessage( ), e );
}
return this;
}
/**
* Converts the given list of Strings to a list of Pattern objects
*
* @param regexps
* A list of regex pattern strings
*
* @exception IllegalArgumentException
* if one of the patterns has invalid regular expression
* syntax
*/
private List<Pattern> getRegExPatterns(List<String> regexps) {
ArrayList<Pattern> patterns = new ArrayList<>();
for (String regexp : regexps) {
String regex = StringUtils.trimToNull(regexp);
if (regex != null) {
// if :empty: is in any of the then return an empty list
if (StringUtils.equals(":empty:", regex)) return new ArrayList<>();
try {
patterns.add(Pattern.compile(regex, Pattern.CASE_INSENSITIVE));
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Illegal Regular Expression Syntax: [" + regex + "] - " + e.getMessage());
}
}
}
return patterns;
}
@Override
protected Object formNeedle(String word) {
Object needle;
if (config.getRegex()) {
try {
needle = Pattern.compile(word);
} catch (PatternSyntaxException pse) {
throw new IllegalArgumentException("Invalid regex syntax for "
+ "pattern \"" + word + "\": " + pse.getMessage());
}
} else if (!config.getCaseSensitive()) {
needle = word.toLowerCase();
} else {
needle = word;
}
return needle;
}
public Object stringToValue(String string) throws ParseException {
try {
return Pattern.compile(string);
} catch (final PatternSyntaxException e) {
throw new ParseException(e.getMessage(), e.getIndex());
}
}
public RegExSearchData(String inputString) {
super(inputString, new byte[0], null);
try {
pattern = Pattern.compile(inputString, Pattern.DOTALL);
} catch (PatternSyntaxException pse) {
errorMessage = pse.getMessage();
}
}
@Override
public RegexPatternOption convert(String input) throws OptionsParsingException {
try {
return RegexPatternOption.create(Pattern.compile(input));
} catch (PatternSyntaxException e) {
throw new OptionsParsingException("Not a valid regular expression: " + e.getMessage());
}
}
void init(String filePattern, PathFilter filter) throws IOException {
try {
userFilter = filter;
pattern = new GlobPattern(filePattern);
}
catch (PatternSyntaxException e) {
// Existing code expects IOException startWith("Illegal file pattern")
throw new IOException("Illegal file pattern: "+ e.getMessage(), e);
}
}
public void setSkipRegexChecksum(String skipRegexChecksum) {
try {
if (skipRegexChecksum != null && skipRegexChecksum.length() > 0) {
this.skipRegexChecksum = Pattern.compile(skipRegexChecksum);
}
} catch (PatternSyntaxException e) {
throw new BuildException("Unable to compile skipRegexChecksum pattern. Reason: "
+ e.getMessage() + " " + skipRegexChecksum, e);
}
}
@Override
public ComparisonResult evaluate(String testText, String... param) {
if (param.length > 0 && param[0] != null && !param[0].equals("")) {
try {
final Pattern pattern = Pattern.compile(param[0].trim());
if (testText != null && evaluate(testText.trim(), pattern)) {
return EQUAL;
}
} catch(PatternSyntaxException e) {
throw new XMLUnitException(e.getMessage(), e);
}
}
return DIFFERENT;
}
@Override
public ExampleSet apply(ExampleSet exampleSet) throws OperatorException {
String splittingRegex = getParameterAsString(PARAMETER_SPLIT_PATTERN);
Pattern splittingPattern = null;
try {
splittingPattern = Pattern.compile(splittingRegex);
} catch (PatternSyntaxException e) {
throw new UserError(this, 206, splittingRegex, e.getMessage());
}
int type = getParameterAsInt(PARAMETER_SPLIT_MODE);
// Until version 6.0.3 there was thrown no UserError when attributes were missing.
// Compatibility check to avoid older processes to fail.
boolean errorOnMissing = getCompatibilityLevel().isAtMost(OPERATOR_VERSION_6_0_3) ? false : true;
for (Attribute attribute : attributeSubsetSelector.getAttributeSubset(exampleSet, false, errorOnMissing)) {
if (attribute.isNominal()) {
switch (type) {
case SPLIT_MODE_ORDERED:
orderedSplit(exampleSet, attribute, splittingPattern);
break;
case SPLIT_MODE_UNORDERED:
default:
unorderedSplit(exampleSet, attribute, splittingPattern);
break;
}
}
}
return exampleSet;
}
@Override
protected Validator<String> createValidator(String model, Converter<String> converter) throws ModelSyntaxException {
String regexpString = parseAndGetOneGroup(model, REGEXP_REGEXP);
try {
return new RegexpValidator(regexpString);
} catch (PatternSyntaxException e) {
throw new ModelSyntaxException(e.getMessage(), e);
}
}
protected static List<String> parseAndGetRegexGroups(String valueToParse, String regexp)
throws ModelSyntaxException {
try {
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(valueToParse);
if (matcher.find()) {
return getMatchedGroups(matcher, matcher.groupCount());
} else {
throw new ModelSyntaxException("Expression '" + valueToParse + "' does not match " + regexp);
}
} catch (PatternSyntaxException e) {
throw new ModelSyntaxException("Internal error, regular expression '" + regexp + "' is invalid: " +
e.getMessage(), e);
}
}
/**
* This method is called during the parser initialization. It parses the parser
* configuration and configures the parser accordingly. It then initializes
* instance variables.
*
* @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) {
setReadCharset(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();
}
@Nullable
@Override
protected ValidationInfo doValidate() {
if (regexCheckBox.isSelected()) {
String regex = regexTextField.getText();
PatternSyntaxException exception = tryCompileRegex(regex);
if (regex.isEmpty() || exception != null) {
String message = "Please specify a valid regex.";
if (exception != null) {
message += " ( " + exception.getMessage() + ")";
}
return new ValidationInfo(message);
}
}
if (parentsCheckBox.isSelected()) {
if (parentsTextField.getText().isEmpty()) {
return new ValidationInfo("Please specify at least one parent.", parentsTextField);
}
}
if (namesCheckBox.isSelected()) {
if (namesTextField.getText().isEmpty()) {
return new ValidationInfo("Please specify at least one name.", namesTextField);
}
}
if (extensionsCheckBox.isSelected()) {
if (extensionsTextField.getText().isEmpty()) {
return new ValidationInfo("Please specify at least one extension.", extensionsTextField);
}
}
if (mayEndWithRadioButton.isSelected() && mayEndWithRadioButton.isEnabled()) {
if (!namesCheckBox.isSelected()) {
return new ValidationInfo("If you select \"May end in\", you need to select the names checkbox.", namesCheckBox);
}
}
if (!getModelConditionFromInput().isValid()) {
return new ValidationInfo("Please select at least one checkbox.");
}
return null;
}
private Matcher createMatcher(
Map<String, String> parameters,
String paramName,
PrintStream debugErr
)
throws PatternSyntaxException
{
Matcher regexMatch = null;
try
{
String regex = parameters.get(paramName);
if (regex != null)
{
Pattern ptrn = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
regexMatch = ptrn.matcher("");
}
}
catch (PatternSyntaxException patternExc)
{
String errorCause;
String excMessage = patternExc.getMessage();
if (excMessage == null)
{
errorCause = "The regular expression library did not return an error cause description.";
}
else
{
errorCause = "The error description returned by the regular expression library is:\n" +
excMessage;
}
printError(
debugErr,
"The regular expression argument for the filter parameter '" + paramName + "' is invalid.",
errorCause,
"Reenter the command with the corrected filter parameter.",
null
);
throw patternExc;
}
return regexMatch;
}
/**
* @param obj1
* @param obj2
* @return true x matches SQL pattern y
* @throws BirtException
* @throws DataException
*/
private static boolean like( Object source, Object pattern, boolean ignorecase ) throws BirtException
{
String sourceStr = null;
sourceStr = (source == null)? "": DataTypeUtil.toLocaleNeutralString( source );
String patternStr;
patternStr = ( pattern == null )? "" : DataTypeUtil.toLocaleNeutralString( pattern );
// As per Bugzilla 115940, LIKE operator's pattern syntax is SQL-like: it
// recognizes '_' and '%'. Backslash '\' escapes the next character.
// Construct a Java RegExp pattern based on input. We need to translate
// unescaped '%' to '.*', and '_' to '.'
// Also need to escape any RegExp metacharacter in the source pattern.
final String reservedChars = "([{^$|)?*+.";
int patternLen = patternStr.length();
StringBuffer buffer = new StringBuffer( patternLen * 2 );
for ( int i = 0; i < patternLen; i++)
{
char c = patternStr.charAt(i);
if ( c == '\\' )
{
// Escape char; copy next character to new pattern if
// it is '\', '%' or '_'
++i;
if ( i < patternLen )
{
c = patternStr.charAt( i );
if ( c == '%' || c == '_' )
buffer.append( c );
else if ( c == '\\' )
buffer.append( "\\\\"); // Need to escape \
}
else
{
buffer.append( "\\\\" ); // Leave last \ and escape it
}
}
else if ( c == '%')
{
buffer.append(".*");
}
else if ( c == '_')
{
buffer.append(".");
}
else
{
// Copy this char to target, escape if it is a metacharacter
if ( reservedChars.indexOf(c) >= 0 )
{
buffer.append('\\');
}
buffer.append(c);
}
}
try
{
String newPatternStr = buffer.toString( );
Pattern p = null;
// Support search in multiple lines
if ( !ignorecase )
{
p = Pattern.compile( newPatternStr, Pattern.DOTALL );
}
else
{
p = Pattern.compile( newPatternStr,
Pattern.DOTALL | Pattern.CASE_INSENSITIVE );
}
Matcher m = p.matcher( sourceStr.toString( ) );
return m.matches( );
}
catch ( PatternSyntaxException e )
{
throw new BirtException( e.getMessage( ) );
}
}