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

Kie issues#1448 - matches() function wrongly behaves - negation syntax translation #6083

Closed
wants to merge 10 commits into from
20 changes: 19 additions & 1 deletion kie-dmn/kie-dmn-feel/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,18 @@
<java.module.name>org.kie.dmn.feel</java.module.name>
<surefire.forkCount>2</surefire.forkCount>
<enforcer.skip>true</enforcer.skip>
<version.net.sf.saxon.Saxon-HE>12.5</version.net.sf.saxon.Saxon-HE>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>Saxon-HE</artifactId>
<version>${version.net.sf.saxon.Saxon-HE}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Internal dependencies -->
<dependency>
Expand All @@ -52,6 +62,10 @@
</dependency>

<!-- External dependencies -->
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>Saxon-HE</artifactId>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
Expand Down Expand Up @@ -135,6 +149,10 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
Copy link
Contributor

Choose a reason for hiding this comment

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

@bncriju I guess this is not required


</dependencies>

Expand All @@ -144,7 +162,7 @@
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
<testResource>
<directory>${project.basedir}/</directory>
<directory>${project.basedir}/../</directory>
Copy link
Contributor

Choose a reason for hiding this comment

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

@bncriju I guess this change is not required

<includes>
<include>ref-dmn-feel-builtin-functions.adoc</include>
</includes>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,11 @@
package org.kie.dmn.feel.runtime.functions;

import java.security.InvalidParameterException;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;

import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity;
import org.kie.dmn.feel.runtime.events.InvalidParametersEvent;
import org.kie.dmn.feel.util.XQueryImplUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -39,21 +36,24 @@ private MatchesFunction() {
super( "matches" );
}

public FEELFnResult<Boolean> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern) {
public FEELFnResult<Boolean> FEELFnResult(@ParameterName("input") String input, @ParameterName("pattern") String pattern) {
Copy link
Contributor

Choose a reason for hiding this comment

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

@bncriju Wrong method name

return invoke( input, pattern, null );
}

public FEELFnResult<Boolean> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern, @ParameterName("flags") String flags) {
try {
return matchFunctionWithFlags(input,pattern,flags);
} catch ( PatternSyntaxException t ) {
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "pattern", "is invalid and can not be compiled", t ) );
} catch (InvalidParameterException t ) {
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, t.getMessage(), "cannot be null", t ) );
} catch (IllegalArgumentException t ) {
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "flags", "contains unknown flags", t ) );
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, t.getMessage(), "cannot be null or is invalid", t ) );
} catch (Throwable t) {
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "pattern", "is invalid and can not be compiled", t ) );
String errorMessage;
if (t.getMessage() != null && !t.getMessage().isEmpty()) {
errorMessage = "Error: " + t.getMessage();
} else {
errorMessage = String.format("Some of the provided parameters might be invalid. Input: '%s', Pattern: '%s', Flags: '%s'",
input, pattern, flags);
}
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, errorMessage, t));
}
}

Expand All @@ -65,37 +65,6 @@ static FEELFnResult<Boolean> matchFunctionWithFlags(String input, String pattern
if ( pattern == null ) {
throw new InvalidParameterException("pattern");
}
final String flagsString;
if (flags != null && !flags.isEmpty()) {
checkFlags(flags);
if(!flags.contains("U")){
flags += "U";
}
flagsString = String.format("(?%s)", flags);
} else {
flagsString = "";
}
log.debug("flagsString: {}", flagsString);
String stringToBeMatched = flagsString + pattern;
log.debug("stringToBeMatched: {}", stringToBeMatched);
Pattern p=Pattern.compile(stringToBeMatched);
Matcher m = p.matcher( input );
boolean matchFound=m.find();
log.debug("matchFound: {}", matchFound);
return FEELFnResult.ofResult(matchFound);
}

static void checkFlags(String flags) {
Set<Character> allowedChars = Set.of('s','i','x','m');
boolean isValidFlag= flags.chars()
.mapToObj(c -> (char) c)
.allMatch(allowedChars::contains)
&& flags.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toSet())
.size() == flags.length();
if(!isValidFlag){
throw new IllegalArgumentException("Not a valid flag parameter " +flags);
}
return FEELFnResult.ofResult(XQueryImplUtil.executeMatchesFunction(input, pattern, flags));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity;
import org.kie.dmn.feel.runtime.events.InvalidParametersEvent;
import org.kie.dmn.feel.util.XQueryImplUtil;

public class ReplaceFunction
extends BaseFEELFunction {
Expand All @@ -30,12 +31,12 @@ private ReplaceFunction() {
super( "replace" );
}

public FEELFnResult<Object> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern,
public FEELFnResult<String> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern,
@ParameterName( "replacement" ) String replacement ) {
return invoke(input, pattern, replacement, null);
}

public FEELFnResult<Object> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern,
public FEELFnResult<String> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern,
@ParameterName( "replacement" ) String replacement, @ParameterName("flags") String flags) {
if ( input == null ) {
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "input", "cannot be null" ) );
Expand All @@ -47,14 +48,7 @@ public FEELFnResult<Object> invoke(@ParameterName("input") String input, @Parame
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "replacement", "cannot be null" ) );
}

final String flagsString;
if (flags != null && !flags.isEmpty()) {
flagsString = "(?" + flags + ")";
} else {
flagsString = "";
}

return FEELFnResult.ofResult( input.replaceAll( flagsString + pattern, replacement ) );
return FEELFnResult.ofResult(String.valueOf(XQueryImplUtil.executeReplaceFunction(input,pattern,replacement,flags)));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.dmn.feel.util;

import net.sf.saxon.s9api.*;

public class XQueryImplUtil {

public static Boolean executeMatchesFunction(String input, String pattern, String flags){
flags = flags == null ? "" : flags;
String xQueryExpression = String.format("matches('%s', '%s', '%s')", input, pattern, flags);
return evaluateXQueryExpression(xQueryExpression, Boolean.class);
}

public static String executeReplaceFunction(String input, String pattern, String replacement, String flags) {
flags = flags == null ? "" : flags;
String xQueryExpression = String.format("replace('%s', '%s', '%s', '%s')", input, pattern, replacement, flags);
return evaluateXQueryExpression(xQueryExpression, String.class);
}

static <T> T evaluateXQueryExpression (String expression, Class<T> expectedTypeResult) {
try {
Processor processor = new Processor(false);
XQueryCompiler compiler = processor.newXQueryCompiler();
XQueryExecutable executable = compiler.compile(expression);
XQueryEvaluator queryEvaluator = executable.load();
XdmItem resultItem = queryEvaluator.evaluateSingle();
return expectedTypeResult.cast((((XdmAtomicValue) resultItem).getValue()));
} catch (ClassCastException | SaxonApiException e) {
throw new IllegalStateException(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,8 @@
import org.mockito.MockedStatic;

import java.security.InvalidParameterException;
import java.util.regex.PatternSyntaxException;

import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException;
import static org.mockito.Mockito.*;

class MatchesFunctionTest {
Expand All @@ -39,11 +37,11 @@ void invokeNull() {

@Test
void invokeUnsupportedFlags() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("foobar", "fo.bar", "g"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", "p"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", "X"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", " "));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", "iU"));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("foobar", "fo.bar", "g"));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", "p"));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", "X"));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", " "));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("abracadabra", "bra", "iU"));
}

@Test
Expand All @@ -63,9 +61,9 @@ void invokeWithoutFlagsNotMatch() {
FunctionTestUtil.assertResult(MatchesFunction.matchFunctionWithFlags("h", "(.)\3",null), false);
FunctionTestUtil.assertResult(MatchesFunction.matchFunctionWithFlags("h", "(.)\2",null), false);
FunctionTestUtil.assertResult(MatchesFunction.matchFunctionWithFlags("input", "\3",null), false);
FunctionTestUtil.assertResult(MatchesFunction.matchFunctionWithFlags("fo\nbar", "(?iU)(?iU)(ab)[|cd]",null), false);
FunctionTestUtil.assertResult(MatchesFunction.matchFunctionWithFlags("fo\nbar", "(?x)(?i)hello world","i"), false);
FunctionTestUtil.assertResult(MatchesFunction.matchFunctionWithFlags("fo\nbar", "(?xi)hello world",null), false);
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("fo\nbar", "(?iU)(?iU)(ab)[|cd]",null));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() ->MatchesFunction.matchFunctionWithFlags("fo\nbar", "(?x)(?i)hello world","i"));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() ->MatchesFunction.matchFunctionWithFlags("fo\nbar", "(?xi)hello world",null));
}

@Test
Expand Down Expand Up @@ -98,33 +96,16 @@ void invokeWithAllFlags() {

@Test
void checkForPatternTest() {
assertThatExceptionOfType(PatternSyntaxException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("foobar", "(abc|def(ghi", "i"));
}

@Test
void checkFlagsTest() {
assertThatNoException().isThrownBy(() -> MatchesFunction.checkFlags("s"));
assertThatNoException().isThrownBy(() -> MatchesFunction.checkFlags("i"));
assertThatNoException().isThrownBy(() -> MatchesFunction.checkFlags("sx"));
assertThatNoException().isThrownBy(() -> MatchesFunction.checkFlags("six"));
assertThatNoException().isThrownBy(() -> MatchesFunction.checkFlags("sixm"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("a"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("sa"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("siU@"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("siUxU"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("ss"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("siiU"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("si U"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> MatchesFunction.checkFlags("U"));
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> MatchesFunction.matchFunctionWithFlags("foobar", "(abc|def(ghi", "i"));
}

@Test
void checkMatchFunctionWithFlagsInvocation() {
MatchesFunction matchesFunctionSpied = spy(MatchesFunction.INSTANCE);
matchesFunctionSpied.invoke("input", "pattern");
matchesFunctionSpied.invoke("input", "pattern",null);
verify(matchesFunctionSpied, times(1)).invoke("input", "pattern", null);
try (MockedStatic<MatchesFunction> matchesFunctionMocked = mockStatic(MatchesFunction.class)) {
matchesFunctionSpied.invoke("input", "pattern");
matchesFunctionSpied.invoke("input", "pattern",null);
matchesFunctionMocked.verify(() -> MatchesFunction.matchFunctionWithFlags("input", "pattern", null));
matchesFunctionSpied.invoke("input", "pattern", "flags");
matchesFunctionMocked.verify(() -> MatchesFunction.matchFunctionWithFlags("input", "pattern", "flags"));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.dmn.feel.util;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class XQueryImplUtilTest {

@Test
void executeMatchesFunctionTest() {
String input = "test";
String pattern = "^test";
String flags = "i";
boolean retrieved = XQueryImplUtil.executeMatchesFunction(input, pattern,
flags);
boolean expected = true;
assertThat(retrieved).isNotNull().isEqualTo(expected);
Copy link
Contributor

Choose a reason for hiding this comment

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

One general comment. Do not reuse variables. Either separate the tests or make a parametric test. a test should be quite simple and very easy to read.


input = "fo\nbar";
pattern = "o.b";
flags = null;
retrieved = XQueryImplUtil.executeMatchesFunction(input, pattern, flags);
expected = false;
assertThat(retrieved).isNotNull().isEqualTo(expected);

input = "TEST";
pattern = "test";
flags = "i";
retrieved = XQueryImplUtil.executeMatchesFunction(input, pattern, flags);
expected = true;
assertThat(retrieved).isNotNull().isEqualTo(expected);
}

@Test
void executeMatchesFunctionInvokingException(){
String input = "test";
String pattern = "^test";
String flags = "g";
assertThatThrownBy(() -> XQueryImplUtil.executeMatchesFunction(input, pattern,
flags)).isInstanceOf(IllegalStateException.class).hasMessageContaining("Unrecognized flag");
}

@Test
void executeReplaceFunctionTest() {
String input = "testString";
String pattern = "^test";
String replacement = "ttt";
String flags = "";
String retrieved = XQueryImplUtil.executeReplaceFunction(input, pattern, replacement,
flags).toString();
String expected = "tttString";
assertThat(retrieved).isNotNull().isEqualTo(expected);

input = "fo\nbar";
pattern = "o.b";
replacement = "ttt";
flags = "s";
retrieved = XQueryImplUtil.executeReplaceFunction(input, pattern, replacement, flags).toString();
expected = "ftttar";
assertThat(retrieved).isNotNull().isEqualTo(expected);
}

}
Loading