idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
7,800
private void objectTypeRow ( final int row , final int column , final String value , final int mergedColStart ) { if ( value . contains ( "$param" ) || value . contains ( "$1" ) ) { throw new DecisionTableParseException ( "It looks like you have snippets in the row that is " + "meant for object declarations." + " Please insert an additional row before the snippets, " + "at cell " + RuleSheetParserUtil . rc2name ( row , column ) ) ; } ActionType action = getActionForColumn ( row , column ) ; if ( mergedColStart == RuleSheetListener . NON_MERGED ) { if ( action . getCode ( ) == Code . CONDITION ) { SourceBuilder src = new LhsBuilder ( row - 1 , column , value ) ; action . setSourceBuilder ( src ) ; this . sourceBuilders . add ( src ) ; } else if ( action . getCode ( ) == Code . ACTION ) { SourceBuilder src = new RhsBuilder ( Code . ACTION , row - 1 , column , value ) ; action . setSourceBuilder ( src ) ; this . sourceBuilders . add ( src ) ; } } else { if ( column == mergedColStart ) { if ( action . getCode ( ) == Code . CONDITION ) { action . setSourceBuilder ( new LhsBuilder ( row - 1 , column , value ) ) ; this . sourceBuilders . add ( action . getSourceBuilder ( ) ) ; } else if ( action . getCode ( ) == Code . ACTION ) { action . setSourceBuilder ( new RhsBuilder ( Code . ACTION , row - 1 , column , value ) ) ; this . sourceBuilders . add ( action . getSourceBuilder ( ) ) ; } } else { ActionType startOfMergeAction = getActionForColumn ( row , mergedColStart ) ; action . setSourceBuilder ( startOfMergeAction . getSourceBuilder ( ) ) ; } } }
This is for handling a row where an object declaration may appear this is the row immediately above the snippets . It may be blank but there has to be a row here .
7,801
private static TokenRange tokenRange ( Token token ) { JavaToken javaToken = token . javaToken ; return new TokenRange ( javaToken , javaToken ) ; }
Create a TokenRange that spans exactly one token
7,802
static Comment createCommentFromToken ( Token token ) { String commentText = token . image ; if ( token . kind == JAVADOC_COMMENT ) { return new JavadocComment ( tokenRange ( token ) , commentText . substring ( 3 , commentText . length ( ) - 2 ) ) ; } else if ( token . kind == MULTI_LINE_COMMENT ) { return new BlockComment ( tokenRange ( token ) , commentText . substring ( 2 , commentText . length ( ) - 2 ) ) ; } else if ( token . kind == SINGLE_LINE_COMMENT ) { Range range = new Range ( pos ( token . beginLine , token . beginColumn ) , pos ( token . endLine , token . endColumn ) ) ; while ( commentText . endsWith ( "\r" ) || commentText . endsWith ( "\n" ) ) { commentText = commentText . substring ( 0 , commentText . length ( ) - 1 ) ; } range = range . withEnd ( pos ( range . begin . line , range . begin . column + commentText . length ( ) ) ) ; LineComment comment = new LineComment ( tokenRange ( token ) , commentText . substring ( 2 ) ) ; comment . setRange ( range ) ; return comment ; } throw new AssertionError ( "Unexpectedly got passed a non-comment token." ) ; }
Since comments are completely captured in a single token including their delimiters deconstruct them here so we can turn them into nodes later on .
7,803
public final synchronized void removeEventListener ( final Class cls ) { for ( int listenerIndex = 0 ; listenerIndex < this . listeners . size ( ) ; ) { E listener = this . listeners . get ( listenerIndex ) ; if ( cls . isAssignableFrom ( listener . getClass ( ) ) ) { this . listeners . remove ( listenerIndex ) ; } else { listenerIndex ++ ; } } }
Removes all event listeners of the specified class . Note that this method needs to be synchonized because it performs two independent operations on the underlying list
7,804
public void makeReferences ( CellRow row , CellCol col , CellSqr sqr ) { this . cellRow = row ; this . cellCol = col ; this . cellSqr = sqr ; this . exCells = new HashSet < Cell > ( ) ; this . exCells . addAll ( this . cellRow . getCells ( ) ) ; this . exCells . addAll ( this . cellCol . getCells ( ) ) ; this . exCells . addAll ( this . cellSqr . getCells ( ) ) ; this . exCells . remove ( this ) ; }
Set references to all cell groups containing this cell .
7,805
public static String getUrl ( Object o ) { if ( o instanceof VerifierRule ) { VerifierRule rule = ( VerifierRule ) o ; return getRuleUrl ( UrlFactory . RULE_FOLDER , rule . getPath ( ) , rule . getName ( ) ) ; } return o . toString ( ) ; }
Finds a link to object if one exists .
7,806
public static Class < ? > loadClass ( String className , ClassLoader classLoader ) { Class cls = ( Class ) classes . get ( className ) ; if ( cls == null ) { try { cls = Class . forName ( className ) ; } catch ( Exception e ) { } if ( cls == null && classLoader != null ) { try { cls = classLoader . loadClass ( className ) ; } catch ( Exception e ) { } } if ( cls == null ) { try { cls = ClassUtils . class . getClassLoader ( ) . loadClass ( className ) ; } catch ( Exception e ) { } } if ( cls == null ) { try { cls = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( Exception e ) { } } if ( cls == null ) { try { cls = ClassLoader . getSystemClassLoader ( ) . loadClass ( className ) ; } catch ( Exception e ) { } } if ( cls != null ) { classes . put ( className , cls ) ; } else { throw new RuntimeException ( "Unable to load class '" + className + "'" ) ; } } return cls ; }
This method will attempt to load the specified Class . It uses a syncrhonized HashMap to cache the reflection Class lookup .
7,807
public static Object instantiateObject ( String className , ClassLoader classLoader ) { Object object ; try { object = loadClass ( className , classLoader ) . newInstance ( ) ; } catch ( Throwable e ) { throw new RuntimeException ( "Unable to instantiate object for class '" + className + "'" , e ) ; } return object ; }
This method will attempt to create an instance of the specified Class . It uses a syncrhonized HashMap to cache the reflection Class lookup .
7,808
public static void addImportStylePatterns ( Map < String , Object > patterns , String str ) { if ( str == null || "" . equals ( str . trim ( ) ) ) { return ; } String [ ] items = str . split ( " " ) ; for ( String item : items ) { String qualifiedNamespace = item . substring ( 0 , item . lastIndexOf ( '.' ) ) . trim ( ) ; String name = item . substring ( item . lastIndexOf ( '.' ) + 1 ) . trim ( ) ; Object object = patterns . get ( qualifiedNamespace ) ; if ( object == null ) { if ( STAR . equals ( name ) ) { patterns . put ( qualifiedNamespace , STAR ) ; } else { List < String > list = new ArrayList < String > ( ) ; list . add ( name ) ; patterns . put ( qualifiedNamespace , list ) ; } } else if ( name . equals ( STAR ) ) { patterns . put ( qualifiedNamespace , STAR ) ; } else { List list = ( List ) object ; if ( ! list . contains ( name ) ) { list . add ( name ) ; } } } }
Populates the import style pattern map from give comma delimited string
7,809
public static boolean isMatched ( Map < String , Object > patterns , String className ) { String qualifiedNamespace = className ; String name = className ; if ( className . indexOf ( '.' ) > 0 ) { qualifiedNamespace = className . substring ( 0 , className . lastIndexOf ( '.' ) ) . trim ( ) ; name = className . substring ( className . lastIndexOf ( '.' ) + 1 ) . trim ( ) ; } else if ( className . indexOf ( '[' ) == 0 ) { qualifiedNamespace = className . substring ( 0 , className . lastIndexOf ( '[' ) ) ; } Object object = patterns . get ( qualifiedNamespace ) ; if ( object == null ) { return true ; } else if ( STAR . equals ( object ) ) { return false ; } else if ( patterns . containsKey ( "*" ) ) { return true ; } else { List list = ( List ) object ; return ! list . contains ( name ) ; } }
Determines if a given full qualified class name matches any import style patterns .
7,810
public static String getPackage ( Class < ? > cls ) { java . lang . Package pkg = cls . isArray ( ) ? cls . getComponentType ( ) . getPackage ( ) : cls . getPackage ( ) ; if ( pkg == null ) { int dotPos ; int dolPos = cls . getName ( ) . indexOf ( '$' ) ; if ( dolPos > 0 ) { dotPos = cls . getName ( ) . substring ( 0 , dolPos ) . lastIndexOf ( '.' ) ; } else { dotPos = cls . getName ( ) . lastIndexOf ( '.' ) ; } if ( dotPos > 0 ) { return cls . getName ( ) . substring ( 0 , dotPos ) ; } else { return "" ; } } else { return pkg . getName ( ) ; } }
Extracts the package name from the given class object
7,811
public boolean add ( AuditLogEntry e ) { if ( filter == null ) { throw new IllegalStateException ( "AuditLogFilter has not been set. Please set before inserting entries." ) ; } if ( filter . accept ( e ) ) { entries . addFirst ( e ) ; return true ; } return false ; }
Add a new AuditLogEntry at the beginning of the list . This is different behaviour to a regular List but it prevents the need to sort entries in descending order .
7,812
public String getMessage ( ) { if ( this . cause == null ) { return super . getMessage ( ) + " Line number: " + this . lineNumber ; } else { return super . getMessage ( ) + " Line number: " + this . lineNumber + ". Caused by: " + this . cause . getMessage ( ) ; } }
This will print out a summary including the line number . It will also print out the cause message if applicable .
7,813
public static URL getURL ( String confName , ClassLoader classLoader , Class cls ) { URL url = null ; String userHome = System . getProperty ( "user.home" ) ; if ( userHome . endsWith ( "\\" ) || userHome . endsWith ( "/" ) ) { url = getURLForFile ( userHome + confName ) ; } else { url = getURLForFile ( userHome + "/" + confName ) ; } if ( url == null ) { url = getURLForFile ( confName ) ; } if ( cls != null ) { URL urlResource = cls . getResource ( confName ) ; if ( urlResource != null ) { url = urlResource ; } } if ( url == null && classLoader != null ) { ClassLoader confClassLoader = classLoader ; if ( confClassLoader != null ) { url = confClassLoader . getResource ( "META-INF/" + confName ) ; } } if ( url == null ) { ClassLoader confClassLoader = ConfFileUtils . class . getClassLoader ( ) ; if ( confClassLoader != null && confClassLoader != classLoader ) { url = confClassLoader . getResource ( "META-INF/" + confName ) ; } } if ( url == null && cls != null ) { ClassLoader confClassLoader = cls . getClassLoader ( ) ; if ( confClassLoader != null && confClassLoader != classLoader ) { url = confClassLoader . getResource ( "META-INF/" + confName ) ; } } if ( url == null ) { ClassLoader confClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( confClassLoader != null && confClassLoader != classLoader ) { url = confClassLoader . getResource ( "META-INF/" + confName ) ; } } if ( url == null ) { ClassLoader confClassLoader = ClassLoader . getSystemClassLoader ( ) ; if ( confClassLoader != null && confClassLoader != classLoader ) { url = confClassLoader . getResource ( "META-INF/" + confName ) ; } } return url ; }
Return the URL for a given conf file
7,814
public static URL getURLForFile ( String fileName ) { URL url = null ; if ( fileName != null ) { File file = new File ( fileName ) ; if ( file != null && file . exists ( ) ) { try { url = file . toURL ( ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( "file.toURL() failed for '" + file + "'" ) ; } } } return url ; }
Return URL for given filename
7,815
public AnnotationDescr addAnnotation ( String name , String value ) { if ( this . annotations == null ) { this . annotations = new HashMap < String , AnnotationDescr > ( ) ; } else { AnnotationDescr existingAnnotation = annotations . get ( name ) ; if ( existingAnnotation != null ) { existingAnnotation . setDuplicated ( ) ; return existingAnnotation ; } } AnnotationDescr annotation = new AnnotationDescr ( name , value ) ; annotation . setResource ( getResource ( ) ) ; return this . annotations . put ( annotation . getName ( ) , annotation ) ; }
Assigns a new annotation to this type with the respective name and value
7,816
public AnnotationDescr getAnnotation ( String name ) { return annotations == null ? null : annotations . get ( name ) ; }
Returns the annotation with the given name
7,817
private void initialize ( ) { addTransformationPair ( GroupElement . NOT , new NotOrTransformation ( ) ) ; addTransformationPair ( GroupElement . EXISTS , new ExistOrTransformation ( ) ) ; addTransformationPair ( GroupElement . AND , new AndOrTransformation ( ) ) ; }
sets up the parent - > child transformations map
7,818
protected void fixClonedDeclarations ( GroupElement and , Map < String , Class < ? > > globals ) { Stack < RuleConditionElement > contextStack = new Stack < RuleConditionElement > ( ) ; DeclarationScopeResolver resolver = new DeclarationScopeResolver ( globals , contextStack ) ; contextStack . push ( and ) ; processElement ( resolver , contextStack , and ) ; contextStack . pop ( ) ; }
During the logic transformation we eventually clone CEs specially patterns and corresponding declarations . So now we need to fix any references to cloned declarations .
7,819
private void processTree ( final GroupElement ce , boolean [ ] result ) throws InvalidPatternException { boolean hasChildOr = false ; ce . pack ( ) ; for ( Object child : ce . getChildren ( ) . toArray ( ) ) { if ( child instanceof GroupElement ) { final GroupElement group = ( GroupElement ) child ; processTree ( group , result ) ; if ( ( group . isOr ( ) || group . isAnd ( ) ) && group . getType ( ) == ce . getType ( ) ) { group . pack ( ce ) ; } else if ( group . isOr ( ) ) { hasChildOr = true ; } } else if ( child instanceof NamedConsequence ) { result [ 0 ] = true ; } else if ( child instanceof Pattern && ( ( Pattern ) child ) . getObjectType ( ) . isEvent ( ) ) { result [ 1 ] = true ; } } if ( hasChildOr ) { applyOrTransformation ( ce ) ; } }
Traverses a Tree during the process it transforms Or nodes moving the upwards and it removes duplicate logic statement this does not include Not nodes .
7,820
public void run ( final StatusUpdate onStatus , final Command onCompletion ) { cancelExistingAnalysis ( ) ; if ( rechecks . isEmpty ( ) ) { if ( onCompletion != null ) { onCompletion . execute ( ) ; return ; } } checkRunner . run ( rechecks , onStatus , onCompletion ) ; rechecks . clear ( ) ; }
Run analysis with feedback
7,821
public static InternalKnowledgeBase newKnowledgeBase ( KieBaseConfiguration conf ) { return newKnowledgeBase ( UUID . randomUUID ( ) . toString ( ) , ( RuleBaseConfiguration ) conf ) ; }
Create a new KnowledgeBase using the given KnowledgeBaseConfiguration
7,822
public static InternalKnowledgeBase newKnowledgeBase ( String kbaseId , KieBaseConfiguration conf ) { return new KnowledgeBaseImpl ( kbaseId , ( RuleBaseConfiguration ) conf ) ; }
Create a new KnowledgeBase using the given KnowledgeBaseConfiguration and the given KnowledgeBase ID .
7,823
public void readLogicalDependency ( final InternalFactHandle handle , final Object object , final Object value , final Activation activation , final PropagationContext context , final RuleImpl rule , final ObjectTypeConf typeConf ) { addLogicalDependency ( handle , object , value , activation , context , rule , typeConf , true ) ; }
Adds a justification for the FactHandle to the justifiedMap .
7,824
private void enableTMS ( Object object , ObjectTypeConf conf ) { Iterator < InternalFactHandle > it = ( ( ClassAwareObjectStore ) ep . getObjectStore ( ) ) . iterateFactHandles ( getActualClass ( object ) ) ; while ( it . hasNext ( ) ) { InternalFactHandle handle = it . next ( ) ; if ( handle != null && handle . getEqualityKey ( ) == null ) { EqualityKey key = new EqualityKey ( handle ) ; handle . setEqualityKey ( key ) ; key . setStatus ( EqualityKey . STATED ) ; put ( key ) ; } } conf . enableTMS ( ) ; }
TMS will be automatically enabled when the first logical insert happens .
7,825
public void setJavaLanguageLevel ( final String languageLevel ) { if ( Arrays . binarySearch ( LANGUAGE_LEVELS , languageLevel ) < 0 ) { throw new RuntimeException ( "value '" + languageLevel + "' is not a valid language level" ) ; } this . languageLevel = languageLevel ; }
You cannot set language level below 1 . 5 as we need static imports 1 . 5 is now the default .
7,826
public void setCompiler ( final CompilerType compiler ) { if ( compiler == CompilerType . ECLIPSE ) { try { Class . forName ( "org.eclipse.jdt.internal.compiler.Compiler" , true , this . conf . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "The Eclipse JDT Core jar is not in the classpath" ) ; } } else if ( compiler == CompilerType . JANINO ) { try { Class . forName ( "org.codehaus.janino.Parser" , true , this . conf . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "The Janino jar is not in the classpath" ) ; } } switch ( compiler ) { case ECLIPSE : this . compiler = CompilerType . ECLIPSE ; break ; case JANINO : this . compiler = CompilerType . JANINO ; break ; case NATIVE : this . compiler = CompilerType . NATIVE ; break ; default : throw new RuntimeException ( "value '" + compiler + "' is not a valid compiler" ) ; } }
Set the compiler to be used when building the rules semantic code blocks . This overrides the default and even what was set as a system property .
7,827
private CompilerType getDefaultCompiler ( ) { try { final String prop = this . conf . getChainedProperties ( ) . getProperty ( JAVA_COMPILER_PROPERTY , "ECLIPSE" ) ; if ( prop . equals ( "NATIVE" ) ) { return CompilerType . NATIVE ; } else if ( prop . equals ( "ECLIPSE" ) ) { return CompilerType . ECLIPSE ; } else if ( prop . equals ( "JANINO" ) ) { return CompilerType . JANINO ; } else { logger . error ( "Drools config: unable to use the drools.compiler property. Using default. It was set to:" + prop ) ; return CompilerType . ECLIPSE ; } } catch ( final SecurityException e ) { logger . error ( "Drools config: unable to read the drools.compiler property. Using default." , e ) ; return CompilerType . ECLIPSE ; } }
This will attempt to read the System property to work out what default to set . This should only be done once when the class is loaded . After that point you will have to programmatically override it .
7,828
private FieldIndex registerFieldIndex ( final int index , final InternalReadAccessor fieldExtractor ) { FieldIndex fieldIndex = null ; if ( this . hashedFieldIndexes == null ) { this . hashedFieldIndexes = new LinkedList < FieldIndex > ( ) ; fieldIndex = new FieldIndex ( index , fieldExtractor ) ; this . hashedFieldIndexes . add ( fieldIndex ) ; } if ( fieldIndex == null ) { fieldIndex = findFieldIndex ( index ) ; } if ( fieldIndex == null ) { fieldIndex = new FieldIndex ( index , fieldExtractor ) ; this . hashedFieldIndexes . add ( fieldIndex ) ; } fieldIndex . increaseCounter ( ) ; return fieldIndex ; }
Returns a FieldIndex which Keeps a count on how many times a particular field is used with an equality check in the sinks .
7,829
protected void doPropagateAssertObject ( InternalFactHandle factHandle , PropagationContext context , InternalWorkingMemory workingMemory , ObjectSink sink ) { sink . assertObject ( factHandle , context , workingMemory ) ; }
This is a Hook method for subclasses to override . Please keep it protected unless you know what you are doing .
7,830
public FEELFnResult < Object > evaluate ( EvaluationContext ctx , Object [ ] params ) { if ( decisionRules . isEmpty ( ) ) { return FEELFnResult . ofError ( new FEELEventBase ( Severity . WARN , "Decision table is empty" , null ) ) ; } Object [ ] actualInputs = resolveActualInputs ( ctx , feel ) ; Either < FEELEvent , Object > actualInputMatch = actualInputsMatchInputValues ( ctx , actualInputs ) ; if ( actualInputMatch . isLeft ( ) ) { return actualInputMatch . cata ( e -> FEELFnResult . ofError ( e ) , e -> FEELFnResult . ofError ( null ) ) ; } List < DTDecisionRule > matches = findMatches ( ctx , actualInputs ) ; if ( ! matches . isEmpty ( ) ) { List < Object > results = evaluateResults ( ctx , feel , actualInputs , matches ) ; Map < Integer , String > msgs = checkResults ( ctx , matches , results ) ; if ( msgs . isEmpty ( ) ) { Object result = hitPolicy . getDti ( ) . dti ( ctx , this , matches , results ) ; return FEELFnResult . ofResult ( result ) ; } else { List < Integer > offending = msgs . keySet ( ) . stream ( ) . collect ( Collectors . toList ( ) ) ; return FEELFnResult . ofError ( new HitPolicyViolationEvent ( Severity . ERROR , "Errors found evaluating decision table '" + getName ( ) + "': \n" + ( msgs . values ( ) . stream ( ) . collect ( Collectors . joining ( "\n" ) ) ) , name , offending ) ) ; } } else { if ( hasDefaultValues ) { Object result = defaultToOutput ( ctx , feel ) ; return FEELFnResult . ofResult ( result ) ; } else { if ( hitPolicy . getDefaultValue ( ) != null ) { return FEELFnResult . ofResult ( hitPolicy . getDefaultValue ( ) ) ; } return FEELFnResult . ofError ( new HitPolicyViolationEvent ( Severity . WARN , "No rule matched for decision table '" + name + "' and no default values were defined. Setting result to null." , name , Collections . EMPTY_LIST ) ) ; } } }
Evaluates this decision table returning the result
7,831
private Either < FEELEvent , Object > actualInputsMatchInputValues ( EvaluationContext ctx , Object [ ] params ) { for ( int i = 0 ; i < params . length ; i ++ ) { final DTInputClause input = inputs . get ( i ) ; if ( input . getInputValues ( ) != null && ! input . getInputValues ( ) . isEmpty ( ) ) { final Object parameter = params [ i ] ; boolean satisfies = input . getInputValues ( ) . stream ( ) . map ( ut -> ut . apply ( ctx , parameter ) ) . filter ( Boolean :: booleanValue ) . findAny ( ) . orElse ( false ) ; if ( ! satisfies ) { String values = input . getInputValuesText ( ) ; return Either . ofLeft ( new InvalidInputEvent ( FEELEvent . Severity . ERROR , input . getInputExpression ( ) + "='" + parameter + "' does not match any of the valid values " + values + " for decision table '" + getName ( ) + "'." , getName ( ) , null , values ) ) ; } } } return Either . ofRight ( true ) ; }
If valid input values are defined check that all parameters match the respective valid inputs
7,832
private List < DTDecisionRule > findMatches ( EvaluationContext ctx , Object [ ] params ) { List < DTDecisionRule > matchingDecisionRules = new ArrayList < > ( ) ; for ( DTDecisionRule decisionRule : decisionRules ) { if ( matches ( ctx , params , decisionRule ) ) { matchingDecisionRules . add ( decisionRule ) ; } } ctx . notifyEvt ( ( ) -> { List < Integer > matches = matchingDecisionRules . stream ( ) . map ( dr -> dr . getIndex ( ) + 1 ) . collect ( Collectors . toList ( ) ) ; return new DecisionTableRulesMatchedEvent ( FEELEvent . Severity . INFO , "Rules matched for decision table '" + getName ( ) + "': " + matches . toString ( ) , getName ( ) , getName ( ) , matches ) ; } ) ; return matchingDecisionRules ; }
Finds all rules that match a given set of parameters
7,833
private boolean matches ( EvaluationContext ctx , Object [ ] params , DTDecisionRule rule ) { for ( int i = 0 ; i < params . length ; i ++ ) { CompiledExpression compiledInput = inputs . get ( i ) . getCompiledInput ( ) ; if ( compiledInput instanceof CompiledFEELExpression ) { ctx . setValue ( "?" , ( ( CompiledFEELExpression ) compiledInput ) . apply ( ctx ) ) ; } if ( ! satisfies ( ctx , params [ i ] , rule . getInputEntry ( ) . get ( i ) ) ) { return false ; } } return true ; }
Checks if the parameters match a single rule
7,834
private boolean satisfies ( EvaluationContext ctx , Object param , UnaryTest test ) { return test . apply ( ctx , param ) ; }
Checks that a given parameter matches a single cell test
7,835
private Object defaultToOutput ( EvaluationContext ctx , FEEL feel ) { Map < String , Object > values = ctx . getAllValues ( ) ; if ( outputs . size ( ) == 1 ) { Object value = feel . evaluate ( outputs . get ( 0 ) . getDefaultValue ( ) , values ) ; return value ; } else { return IntStream . range ( 0 , outputs . size ( ) ) . boxed ( ) . collect ( toMap ( i -> outputs . get ( i ) . getName ( ) , i -> feel . evaluate ( outputs . get ( i ) . getDefaultValue ( ) , values ) ) ) ; } }
No hits matched for the DT so calculate result based on default outputs
7,836
public void marshalMarshall ( Object o , OutputStream out ) { try { XStream xStream = newXStream ( ) ; out . write ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . getBytes ( ) ) ; OutputStreamWriter ows = new OutputStreamWriter ( out , "UTF-8" ) ; xStream . toXML ( o , ows ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Unnecessary as was a tentative UTF - 8 preamble output but still not working .
7,837
public static String formatXml ( String xml ) { try { Transformer serializer = SAXTransformerFactory . newInstance ( ) . newTransformer ( ) ; serializer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; serializer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "2" ) ; Source xmlSource = new SAXSource ( new InputSource ( new ByteArrayInputStream ( xml . getBytes ( ) ) ) ) ; StreamResult res = new StreamResult ( new ByteArrayOutputStream ( ) ) ; serializer . transform ( xmlSource , res ) ; return new String ( ( ( ByteArrayOutputStream ) res . getOutputStream ( ) ) . toByteArray ( ) ) ; } catch ( Exception e ) { return xml ; } }
Unnecessary as the stax driver custom anon as static definition is embedding the indentation .
7,838
public void setDMNLabel ( org . kie . dmn . model . api . dmndi . DMNLabel value ) { this . dmnLabel = value ; }
Sets the value of the dmnLabel property .
7,839
public ClassDefinition generateDeclaredBean ( AbstractClassTypeDeclarationDescr typeDescr , TypeDeclaration type , PackageRegistry pkgRegistry , List < TypeDefinition > unresolvedTypeDefinitions , Map < String , AbstractClassTypeDeclarationDescr > unprocesseableDescrs ) { ClassDefinition def = createClassDefinition ( typeDescr , type ) ; boolean success = true ; success &= wireAnnotationDefs ( typeDescr , type , def , pkgRegistry . getTypeResolver ( ) ) ; success &= wireEnumLiteralDefs ( typeDescr , type , def ) ; success &= wireFields ( typeDescr , type , def , pkgRegistry , unresolvedTypeDefinitions ) ; if ( ! success ) { unprocesseableDescrs . put ( typeDescr . getType ( ) . getFullName ( ) , typeDescr ) ; } type . setTypeClassDef ( def ) ; return def ; }
Generates a bean and adds it to the composite class loader that everything is using .
7,840
public void writeToDisk ( ) { if ( ! initialized ) { initializeLog ( ) ; } Writer writer = null ; try { FileOutputStream fileOut = new FileOutputStream ( this . fileName + ( this . nbOfFile == 0 ? ".log" : this . nbOfFile + ".log" ) , true ) ; writer = new OutputStreamWriter ( fileOut , IoUtils . UTF8_CHARSET ) ; final XStream xstream = createTrustingXStream ( ) ; WorkingMemoryLog log = null ; synchronized ( this . events ) { log = new WorkingMemoryLog ( new ArrayList < LogEvent > ( this . events ) ) ; clear ( ) ; } writer . write ( xstream . toXML ( log ) + "\n" ) ; } catch ( final FileNotFoundException exc ) { throw new RuntimeException ( "Could not create the log file. Please make sure that directory that the log file should be placed in does exist." ) ; } catch ( final Throwable t ) { logger . error ( "error" , t ) ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( Exception e ) { } } } if ( terminate ) { closeLog ( ) ; terminate = true ; } else if ( split ) { closeLog ( ) ; this . nbOfFile ++ ; initialized = false ; } }
All events in the log are written to file . The log is automatically cleared afterwards .
7,841
public static Object and ( Object left , Object right , EvaluationContext ctx ) { Boolean l = EvalHelper . getBooleanOrNull ( left ) ; Boolean r = EvalHelper . getBooleanOrNull ( right ) ; if ( ( l == null && r == null ) || ( l == null && r == true ) || ( r == null && l == true ) ) { return null ; } else if ( l == null || r == null ) { return false ; } return l && r ; }
Implements the ternary logic AND operation
7,842
public List < KnowledgeBuilderResult > addResults ( List < KnowledgeBuilderResult > list ) { if ( list == null ) { list = new ArrayList < KnowledgeBuilderResult > ( ) ; } for ( Dialect dialect : map . values ( ) ) { List < KnowledgeBuilderResult > results = dialect . getResults ( ) ; if ( results != null ) { for ( KnowledgeBuilderResult result : results ) { if ( ! list . contains ( result ) ) { list . add ( result ) ; } } dialect . clearResults ( ) ; } } return list ; }
Add all registered Dialect results to the provided List .
7,843
public void addImport ( ImportDescr importDescr ) { for ( Dialect dialect : this . map . values ( ) ) { dialect . addImport ( importDescr ) ; } }
Iterates all registered dialects informing them of an import added to the PackageBuilder
7,844
public void addStaticImport ( ImportDescr importDescr ) { for ( Dialect dialect : this . map . values ( ) ) { dialect . addStaticImport ( importDescr ) ; } }
Iterates all registered dialects informing them of a static imports added to the PackageBuilder
7,845
public void deployArtifact ( AFReleaseId releaseId , InternalKieModule kieModule , File pomfile ) { RemoteRepository repository = getRemoteRepositoryFromDistributionManagement ( pomfile ) ; if ( repository == null ) { log . warn ( "No Distribution Management configured: unknown repository" ) ; return ; } deployArtifact ( repository , releaseId , kieModule , pomfile ) ; }
Deploys the kjar in the given kieModule on the remote repository defined in the distributionManagement tag of the provided pom file . If the pom file doesn t define a distributionManagement no deployment will be performed and a warning message will be logged .
7,846
public void deployArtifact ( RemoteRepository repository , AFReleaseId releaseId , InternalKieModule kieModule , File pomfile ) { File jarFile = bytesToFile ( releaseId , kieModule . getBytes ( ) , ".jar" ) ; deployArtifact ( repository , releaseId , jarFile , pomfile ) ; }
Deploys the kjar in the given kieModule on a remote repository .
7,847
public void installArtifact ( AFReleaseId releaseId , InternalKieModule kieModule , File pomfile ) { File jarFile = bytesToFile ( releaseId , kieModule . getBytes ( ) , ".jar" ) ; installArtifact ( releaseId , jarFile , pomfile ) ; }
Installs the kjar in the given kieModule into the local repository .
7,848
@ Generated ( "com.github.javaparser.generator.core.node.PropertyGenerator" ) public NullSafeFieldAccessExpr setScope ( final Expression scope ) { assertNotNull ( scope ) ; if ( scope == this . scope ) { return ( NullSafeFieldAccessExpr ) this ; } notifyPropertyChange ( ObservableProperty . SCOPE , this . scope , scope ) ; if ( this . scope != null ) { this . scope . setParentNode ( null ) ; } this . scope = scope ; setAsParentNodeOf ( scope ) ; return this ; }
Sets the scope
7,849
@ Generated ( "com.github.javaparser.generator.core.node.PropertyGenerator" ) public NullSafeFieldAccessExpr setTypeArguments ( final NodeList < Type > typeArguments ) { if ( typeArguments == this . typeArguments ) { return ( NullSafeFieldAccessExpr ) this ; } notifyPropertyChange ( ObservableProperty . TYPE_ARGUMENTS , this . typeArguments , typeArguments ) ; if ( this . typeArguments != null ) { this . typeArguments . setParentNode ( null ) ; } this . typeArguments = typeArguments ; setAsParentNodeOf ( typeArguments ) ; return this ; }
Sets the type arguments
7,850
public void compileNode ( DecisionService ds , DMNCompilerImpl compiler , DMNModelImpl model ) { DMNType type = null ; if ( ds . getVariable ( ) == null ) { DMNCompilerHelper . reportMissingVariable ( model , ds , ds , Msg . MISSING_VARIABLE_FOR_DS ) ; return ; } DMNCompilerHelper . checkVariableName ( model , ds , ds . getName ( ) ) ; if ( ds . getVariable ( ) != null && ds . getVariable ( ) . getTypeRef ( ) != null ) { type = compiler . resolveTypeRef ( model , ds , ds . getVariable ( ) , ds . getVariable ( ) . getTypeRef ( ) ) ; } else { type = compiler . resolveTypeRef ( model , ds , ds , null ) ; } DecisionServiceNodeImpl bkmn = new DecisionServiceNodeImpl ( ds , type ) ; model . addDecisionService ( bkmn ) ; }
backport of DMN v1 . 1
7,851
private static String inputQualifiedNamePrefix ( DMNNode input , DMNModelImpl model ) { if ( input . getModelNamespace ( ) . equals ( model . getNamespace ( ) ) ) { return null ; } else { Optional < String > importAlias = model . getImportAliasFor ( input . getModelNamespace ( ) , input . getModelName ( ) ) ; if ( ! importAlias . isPresent ( ) ) { MsgUtil . reportMessage ( LOG , DMNMessage . Severity . ERROR , ( ( DMNBaseNode ) input ) . getSource ( ) , model , null , null , Msg . IMPORT_NOT_FOUND_FOR_NODE_MISSING_ALIAS , new QName ( input . getModelNamespace ( ) , input . getModelName ( ) ) , ( ( DMNBaseNode ) input ) . getSource ( ) ) ; return null ; } return importAlias . get ( ) ; } }
DMN v1 . 2 specification chapter 10 . 4 Execution Semantics of Decision Services The qualified name of an element named E that is defined in the same decision model as S is simply E . Otherwise the qualified name is I . E where I is the name of the import element that refers to the model where E is defined .
7,852
public GuidedDecisionTable52 upgrade ( GuidedDecisionTable52 source ) { final GuidedDecisionTable52 destination = source ; final int iRowNumberColumnIndex = 0 ; Integer iSalienceColumnIndex = null ; Integer iDurationColumnIndex = null ; List < BaseColumn > allColumns = destination . getExpandedColumns ( ) ; for ( int iCol = 0 ; iCol < allColumns . size ( ) ; iCol ++ ) { final BaseColumn column = allColumns . get ( iCol ) ; if ( column instanceof AttributeCol52 ) { AttributeCol52 attributeCol = ( AttributeCol52 ) column ; final String attributeName = attributeCol . getAttribute ( ) ; if ( GuidedDecisionTable52 . SALIENCE_ATTR . equals ( attributeName ) ) { iSalienceColumnIndex = iCol ; } else if ( GuidedDecisionTable52 . DURATION_ATTR . equals ( attributeName ) ) { iDurationColumnIndex = iCol ; } } } for ( List < DTCellValue52 > row : destination . getData ( ) ) { final int rowNumberValue = row . get ( iRowNumberColumnIndex ) . getNumericValue ( ) . intValue ( ) ; row . get ( iRowNumberColumnIndex ) . setNumericValue ( rowNumberValue ) ; if ( iSalienceColumnIndex != null ) { final Number salienceValue = row . get ( iSalienceColumnIndex ) . getNumericValue ( ) ; if ( salienceValue == null ) { row . get ( iSalienceColumnIndex ) . setNumericValue ( ( Integer ) null ) ; } else { row . get ( iSalienceColumnIndex ) . setNumericValue ( salienceValue . intValue ( ) ) ; } } if ( iDurationColumnIndex != null ) { final Number durationValue = row . get ( iDurationColumnIndex ) . getNumericValue ( ) ; if ( durationValue == null ) { row . get ( iDurationColumnIndex ) . setNumericValue ( ( Long ) null ) ; } else { row . get ( iDurationColumnIndex ) . setNumericValue ( durationValue . longValue ( ) ) ; } } } return destination ; }
Convert the data - types in the Decision Table model
7,853
public static void addRule ( TerminalNode tn , Collection < InternalWorkingMemory > wms , InternalKnowledgeBase kBase ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Adding Rule {}" , tn . getRule ( ) . getName ( ) ) ; } boolean hasProtos = kBase . hasSegmentPrototypes ( ) ; boolean hasWms = ! wms . isEmpty ( ) ; if ( ! hasProtos && ! hasWms ) { return ; } RuleImpl rule = tn . getRule ( ) ; LeftTupleNode firstSplit = getNetworkSplitPoint ( tn ) ; PathEndNodes pathEndNodes = getPathEndNodes ( kBase , firstSplit , tn , rule , hasProtos , hasWms ) ; for ( InternalWorkingMemory wm : wms ) { wm . flushPropagations ( ) ; if ( NodeTypeEnums . LeftInputAdapterNode == firstSplit . getType ( ) && firstSplit . getAssociationsSize ( ) == 1 ) { insertLiaFacts ( firstSplit , wm ) ; } else { PathEndNodeMemories tnms = getPathEndMemories ( wm , pathEndNodes ) ; if ( tnms . subjectPmem == null ) { continue ; } Map < PathMemory , SegmentMemory [ ] > prevSmemsLookup = reInitPathMemories ( tnms . otherPmems , null ) ; Set < SegmentMemory > smemsToNotify = handleExistingPaths ( tn , prevSmemsLookup , tnms . otherPmems , wm , ExistingPathStrategy . ADD_STRATEGY ) ; addNewPaths ( wm , smemsToNotify , tnms . subjectPmems ) ; processLeftTuples ( firstSplit , wm , true , rule ) ; notifySegments ( smemsToNotify , wm ) ; } } if ( hasWms ) { insertFacts ( pathEndNodes , wms ) ; } else { for ( PathEndNode node : pathEndNodes . otherEndNodes ) { node . resetPathMemSpec ( null ) ; } } }
This method is called after the rule nodes have been added to the network For add tuples are processed after the segments and pmems have been adjusted
7,854
public static void removeRule ( TerminalNode tn , Collection < InternalWorkingMemory > wms , InternalKnowledgeBase kBase ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Removing Rule {}" , tn . getRule ( ) . getName ( ) ) ; } boolean hasProtos = kBase . hasSegmentPrototypes ( ) ; boolean hasWms = ! wms . isEmpty ( ) ; if ( ! hasProtos && ! hasWms ) { return ; } RuleImpl rule = tn . getRule ( ) ; LeftTupleNode firstSplit = getNetworkSplitPoint ( tn ) ; PathEndNodes pathEndNodes = getPathEndNodes ( kBase , firstSplit , tn , rule , hasProtos , hasWms ) ; for ( InternalWorkingMemory wm : wms ) { wm . flushPropagations ( ) ; PathEndNodeMemories tnms = getPathEndMemories ( wm , pathEndNodes ) ; if ( ! tnms . subjectPmems . isEmpty ( ) ) { if ( NodeTypeEnums . LeftInputAdapterNode == firstSplit . getType ( ) && firstSplit . getAssociationsSize ( ) == 1 ) { if ( tnms . subjectPmem != null ) { flushStagedTuples ( firstSplit , tnms . subjectPmem , wm ) ; } processLeftTuples ( firstSplit , wm , false , tn . getRule ( ) ) ; removeNewPaths ( wm , tnms . subjectPmems ) ; } else { flushStagedTuples ( tn , tnms . subjectPmem , pathEndNodes , wm ) ; processLeftTuples ( firstSplit , wm , false , tn . getRule ( ) ) ; removeNewPaths ( wm , tnms . subjectPmems ) ; Map < PathMemory , SegmentMemory [ ] > prevSmemsLookup = reInitPathMemories ( tnms . otherPmems , tn ) ; Set < SegmentMemory > smemsToNotify = handleExistingPaths ( tn , prevSmemsLookup , tnms . otherPmems , wm , ExistingPathStrategy . REMOVE_STRATEGY ) ; notifySegments ( smemsToNotify , wm ) ; } } if ( tnms . subjectPmem != null && tnms . subjectPmem . isInitialized ( ) && tnms . subjectPmem . getRuleAgendaItem ( ) . isQueued ( ) ) { tnms . subjectPmem . getRuleAgendaItem ( ) . dequeue ( ) ; } } }
This method is called before the rule nodes are removed from the network . For remove tuples are processed before the segments and pmems have been adjusted
7,855
private static LeftTuple insertPeerLeftTuple ( LeftTuple lt , LeftTupleSinkNode node , InternalWorkingMemory wm ) { LeftInputAdapterNode . LiaNodeMemory liaMem = null ; if ( node . getLeftTupleSource ( ) . getType ( ) == NodeTypeEnums . LeftInputAdapterNode ) { liaMem = wm . getNodeMemory ( ( ( LeftInputAdapterNode ) node . getLeftTupleSource ( ) ) ) ; } LeftTuple peer = node . createPeer ( lt ) ; Memory memory = wm . getNodeMemories ( ) . peekNodeMemory ( node ) ; if ( memory == null || memory . getSegmentMemory ( ) == null ) { throw new IllegalStateException ( "Defensive Programming: this should not be possilbe, as the addRule code should init child segments if they are needed " ) ; } if ( liaMem == null ) { memory . getSegmentMemory ( ) . getStagedLeftTuples ( ) . addInsert ( peer ) ; } else { LeftInputAdapterNode . doInsertSegmentMemory ( wm , true , liaMem , memory . getSegmentMemory ( ) , peer , node . getLeftTupleSource ( ) . isStreamMode ( ) ) ; } return peer ; }
Create all missing peers
7,856
public void addAlphaConstraint ( AlphaNodeFieldConstraint constraint ) { if ( constraint != null ) { AlphaNodeFieldConstraint [ ] tmp = this . alphaConstraints ; this . alphaConstraints = new AlphaNodeFieldConstraint [ tmp . length + 1 ] ; System . arraycopy ( tmp , 0 , this . alphaConstraints , 0 , tmp . length ) ; this . alphaConstraints [ this . alphaConstraints . length - 1 ] = constraint ; this . updateRequiredDeclarations ( constraint ) ; } }
Adds an alpha constraint to the multi field OR constraint
7,857
public void addBetaConstraint ( BetaNodeFieldConstraint constraint ) { if ( constraint != null ) { BetaNodeFieldConstraint [ ] tmp = this . betaConstraints ; this . betaConstraints = new BetaNodeFieldConstraint [ tmp . length + 1 ] ; System . arraycopy ( tmp , 0 , this . betaConstraints , 0 , tmp . length ) ; this . betaConstraints [ this . betaConstraints . length - 1 ] = constraint ; this . updateRequiredDeclarations ( constraint ) ; this . setType ( Constraint . ConstraintType . BETA ) ; } }
Adds a beta constraint to this multi field OR constraint
7,858
public void addConstraint ( Constraint constraint ) { if ( ConstraintType . ALPHA . equals ( constraint . getType ( ) ) ) { this . addAlphaConstraint ( ( AlphaNodeFieldConstraint ) constraint ) ; } else if ( ConstraintType . BETA . equals ( constraint . getType ( ) ) ) { this . addBetaConstraint ( ( BetaNodeFieldConstraint ) constraint ) ; } else { throw new RuntimeException ( "Constraint type MUST be known in advance." ) ; } }
Adds a constraint too all lists it belongs to by checking for its type
7,859
protected void updateRequiredDeclarations ( Constraint constraint ) { Declaration [ ] decs = constraint . getRequiredDeclarations ( ) ; if ( decs != null && decs . length > 0 ) { for ( Declaration dec1 : decs ) { Declaration dec = dec1 ; for ( Declaration requiredDeclaration : this . requiredDeclarations ) { if ( dec . equals ( requiredDeclaration ) ) { dec = null ; break ; } } if ( dec != null ) { Declaration [ ] tmp = this . requiredDeclarations ; this . requiredDeclarations = new Declaration [ tmp . length + 1 ] ; System . arraycopy ( tmp , 0 , this . requiredDeclarations , 0 , tmp . length ) ; this . requiredDeclarations [ this . requiredDeclarations . length - 1 ] = dec ; } } } }
Updades the cached required declaration array
7,860
public FunctionKind getKind ( ) { String kindValueOnV11 = this . getAdditionalAttributes ( ) . get ( KIND_QNAME ) ; if ( kindValueOnV11 == null || kindValueOnV11 . isEmpty ( ) ) { return FunctionKind . FEEL ; } else { switch ( kindValueOnV11 ) { case "F" : return FunctionKind . FEEL ; case "J" : return FunctionKind . JAVA ; case "P" : return FunctionKind . PMML ; default : return FunctionKind . FEEL ; } } }
Align to DMN v1 . 2
7,861
public RiaNodeMemory createMemory ( final RuleBaseConfiguration config , InternalWorkingMemory wm ) { RiaNodeMemory rianMem = new RiaNodeMemory ( ) ; RiaPathMemory pmem = new RiaPathMemory ( this , wm ) ; PathMemSpec pathMemSpec = getPathMemSpec ( ) ; pmem . setAllLinkedMaskTest ( pathMemSpec . allLinkedTestMask ) ; pmem . setSegmentMemories ( new SegmentMemory [ pathMemSpec . smemCount ] ) ; rianMem . setRiaPathMemory ( pmem ) ; return rianMem ; }
Creates and return the node memory
7,862
public Object get ( final Declaration declaration ) { return declaration . getValue ( ( InternalWorkingMemory ) workingMemory , getObject ( getFactHandle ( declaration ) ) ) ; }
Return the Object for the given Declaration .
7,863
public FactHandle [ ] getFactHandles ( ) { int size = size ( ) ; FactHandle [ ] subArray = new FactHandle [ size ] ; System . arraycopy ( this . row . getHandles ( ) , 1 , subArray , 0 , size ) ; return subArray ; }
Return the FactHandles for the Tuple .
7,864
@ SuppressWarnings ( "unchecked" ) public void addEvaluatorDefinition ( String className ) { try { Class < EvaluatorDefinition > defClass = ( Class < EvaluatorDefinition > ) this . classloader . loadClass ( className ) ; EvaluatorDefinition def = defClass . newInstance ( ) ; addEvaluatorDefinition ( def ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "Class not found for evaluator definition: " + className , e ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( "Error instantiating class for evaluator definition: " + className , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Illegal access instantiating class for evaluator definition: " + className , e ) ; } }
Adds an evaluator definition class to the registry using the evaluator class name . The class will be loaded and the corresponting evaluator ID will be added to the registry . In case there exists an implementation for that ID already the new implementation will replace the previous one .
7,865
public void addEvaluatorDefinition ( EvaluatorDefinition def ) { for ( String id : def . getEvaluatorIds ( ) ) { this . evaluators . put ( id , def ) ; } }
Adds an evaluator definition class to the registry . In case there exists an implementation for that evaluator ID already the new implementation will replace the previous one .
7,866
public GuidedDecisionTable52 upgrade ( GuidedDecisionTable52 source ) { final GuidedDecisionTable52 destination = source ; for ( BaseColumn column : source . getExpandedColumns ( ) ) { DTColumnConfig52 dtColumn = null ; if ( column instanceof MetadataCol52 ) { dtColumn = ( DTColumnConfig52 ) column ; } else if ( column instanceof AttributeCol52 ) { dtColumn = ( DTColumnConfig52 ) column ; } else if ( column instanceof ConditionCol52 ) { dtColumn = ( DTColumnConfig52 ) column ; } else if ( column instanceof ActionCol52 ) { dtColumn = ( DTColumnConfig52 ) column ; } if ( dtColumn instanceof LimitedEntryCol ) { dtColumn = null ; } if ( dtColumn instanceof BRLVariableColumn ) { dtColumn = null ; } if ( dtColumn != null ) { final String legacyDefaultValue = dtColumn . defaultValue ; if ( legacyDefaultValue != null ) { dtColumn . setDefaultValue ( new DTCellValue52 ( legacyDefaultValue ) ) ; dtColumn . defaultValue = null ; } } } return destination ; }
Convert the Default Values in the Decision Table model
7,867
public List < DMNDiagram > getDMNDiagram ( ) { if ( dmnDiagram == null ) { dmnDiagram = new ArrayList < DMNDiagram > ( ) ; } return this . dmnDiagram ; }
Gets the value of the dmnDiagram property .
7,868
public List < DMNStyle > getDMNStyle ( ) { if ( dmnStyle == null ) { dmnStyle = new ArrayList < DMNStyle > ( ) ; } return this . dmnStyle ; }
Gets the value of the dmnStyle property .
7,869
public static String getUniqueLegalName ( final String packageName , final String name , final int seed , final String ext , final String prefix , final ResourceReader src ) { final String newName = prefix + "_" + normalizeRuleName ( name ) ; if ( ext . equals ( "java" ) ) { return newName + Math . abs ( seed ) ; } final String fileName = packageName . replace ( '.' , '/' ) + "/" + newName ; if ( src == null || ! src . isAvailable ( fileName + "." + ext ) ) return newName ; int counter = - 1 ; while ( true ) { counter ++ ; final String actualName = fileName + "_" + counter + "." + ext ; if ( ! src . isAvailable ( actualName ) ) break ; } return newName + "_" + counter ; }
Takes a given name and makes sure that its legal and doesn t already exist . If the file exists it increases counter appender untill it is unique .
7,870
public EvaluationContextImpl newEvaluationContext ( Collection < FEELEventListener > listeners , Map < String , Object > inputVariables ) { return newEvaluationContext ( this . classLoader , listeners , inputVariables ) ; }
Creates a new EvaluationContext using this FEEL instance classloader and the supplied parameters listeners and inputVariables
7,871
public EvaluationContextImpl newEvaluationContext ( ClassLoader cl , Collection < FEELEventListener > listeners , Map < String , Object > inputVariables ) { FEELEventListenersManager eventsManager = getEventsManager ( listeners ) ; EvaluationContextImpl ctx = new EvaluationContextImpl ( cl , eventsManager , inputVariables . size ( ) ) ; if ( customFrame . isPresent ( ) ) { ExecutionFrameImpl globalFrame = ( ExecutionFrameImpl ) ctx . pop ( ) ; ExecutionFrameImpl interveawedFrame = customFrame . get ( ) ; interveawedFrame . setParentFrame ( ctx . peek ( ) ) ; globalFrame . setParentFrame ( interveawedFrame ) ; ctx . push ( interveawedFrame ) ; ctx . push ( globalFrame ) ; } ctx . setValues ( inputVariables ) ; return ctx ; }
Creates a new EvaluationContext with the supplied classloader and the supplied parameters listeners and inputVariables
7,872
public Memory getNodeMemory ( MemoryFactory node , InternalWorkingMemory wm ) { if ( node . getMemoryId ( ) >= this . memories . length ( ) ) { resize ( node ) ; } Memory memory = this . memories . get ( node . getMemoryId ( ) ) ; if ( memory == null ) { memory = createNodeMemory ( node , wm ) ; } return memory ; }
The implementation tries to delay locking as much as possible by running some potentially unsafe operations out of the critical session . In case it fails the checks it will move into the critical sessions and re - check everything before effectively doing any change on data structures .
7,873
private Memory createNodeMemory ( MemoryFactory node , InternalWorkingMemory wm ) { try { this . lock . lock ( ) ; Memory memory = this . memories . get ( node . getMemoryId ( ) ) ; if ( memory == null ) { memory = node . createMemory ( this . kBase . getConfiguration ( ) , wm ) ; if ( ! this . memories . compareAndSet ( node . getMemoryId ( ) , null , memory ) ) { memory = this . memories . get ( node . getMemoryId ( ) ) ; } } return memory ; } finally { this . lock . unlock ( ) ; } }
Checks if a memory does not exists for the given node and creates it .
7,874
public void setDMNDecisionServiceDividerLine ( org . kie . dmn . model . api . dmndi . DMNDecisionServiceDividerLine value ) { this . dmnDecisionServiceDividerLine = value ; }
Sets the value of the dmnDecisionServiceDividerLine property .
7,875
public boolean evaluate ( InternalWorkingMemory workingMemory , Object left , Object right ) { Object leftValue = leftTimestamp != null ? leftTimestamp : left ; Object rightValue = rightTimestamp != null ? rightTimestamp : right ; return rightLiteral ? evaluator . evaluate ( workingMemory , new ConstantValueReader ( leftValue ) , dummyFactHandleOf ( leftValue ) , new ObjectFieldImpl ( rightValue ) ) : evaluator . evaluate ( workingMemory , new ConstantValueReader ( leftValue ) , dummyFactHandleOf ( leftValue ) , new ConstantValueReader ( rightValue ) , dummyFactHandleOf ( rightValue ) ) ; }
This method is called when operators are rewritten as function calls . For instance
7,876
public FactPattern getLHSBoundFact ( final String var ) { if ( this . lhs == null ) { return null ; } for ( int i = 0 ; i < this . lhs . length ; i ++ ) { IPattern pat = this . lhs [ i ] ; if ( pat instanceof FromCompositeFactPattern ) { pat = ( ( FromCompositeFactPattern ) pat ) . getFactPattern ( ) ; } if ( pat instanceof FactPattern ) { final FactPattern p = ( FactPattern ) pat ; if ( p . getBoundName ( ) != null && var . equals ( p . getBoundName ( ) ) ) { return p ; } } } return null ; }
This will return the FactPattern that a variable is bound Eto .
7,877
public SingleFieldConstraint getLHSBoundField ( final String var ) { if ( this . lhs == null ) { return null ; } for ( int i = 0 ; i < this . lhs . length ; i ++ ) { IPattern pat = this . lhs [ i ] ; SingleFieldConstraint fieldConstraint = getLHSBoundField ( pat , var ) ; if ( fieldConstraint != null ) { return fieldConstraint ; } } return null ; }
This will return the FieldConstraint that a variable is bound to .
7,878
public String getLHSBindingType ( final String var ) { if ( this . lhs == null ) { return null ; } for ( int i = 0 ; i < this . lhs . length ; i ++ ) { String type = getLHSBindingType ( this . lhs [ i ] , var ) ; if ( type != null ) { return type ; } } return null ; }
Get the data - type associated with the binding
7,879
public ActionInsertFact getRHSBoundFact ( final String var ) { if ( this . rhs == null ) { return null ; } for ( int i = 0 ; i < this . rhs . length ; i ++ ) { if ( this . rhs [ i ] instanceof ActionInsertFact ) { final ActionInsertFact p = ( ActionInsertFact ) this . rhs [ i ] ; if ( p . getBoundName ( ) != null && var . equals ( p . getBoundName ( ) ) ) { return p ; } } } return null ; }
This will return the ActionInsertFact that a variable is bound to .
7,880
public FactPattern getLHSParentFactPatternForBinding ( final String var ) { if ( this . lhs == null ) { return null ; } for ( int i = 0 ; i < this . lhs . length ; i ++ ) { IPattern pat = this . lhs [ i ] ; if ( pat instanceof FromCompositeFactPattern ) { pat = ( ( FromCompositeFactPattern ) pat ) . getFactPattern ( ) ; } if ( pat instanceof FactPattern ) { final FactPattern p = ( FactPattern ) pat ; if ( p . getBoundName ( ) != null && var . equals ( p . getBoundName ( ) ) ) { return p ; } for ( int j = 0 ; j < p . getFieldConstraints ( ) . length ; j ++ ) { FieldConstraint fc = p . getFieldConstraints ( ) [ j ] ; List < String > fieldBindings = getFieldBinding ( fc ) ; if ( fieldBindings . contains ( var ) ) { return p ; } } } } return null ; }
This will return the FactPattern that a variable is bound to . If the variable is bound to a FieldConstraint the parent FactPattern will be returned .
7,881
public List < String > getAllRHSVariables ( ) { List < String > result = new ArrayList < String > ( ) ; for ( int i = 0 ; i < this . rhs . length ; i ++ ) { IAction pat = this . rhs [ i ] ; if ( pat instanceof ActionInsertFact ) { ActionInsertFact fact = ( ActionInsertFact ) pat ; if ( fact . isBound ( ) ) { result . add ( fact . getBoundName ( ) ) ; } } } return result ; }
This will get a list of all RHS bound variables .
7,882
public RuleMetadata getMetaData ( String attributeName ) { if ( metadataList != null && attributeName != null ) { for ( int i = 0 ; i < metadataList . length ; i ++ ) { if ( attributeName . equals ( metadataList [ i ] . getAttributeName ( ) ) ) { return metadataList [ i ] ; } } } return null ; }
Locate metadata element
7,883
public boolean updateMetadata ( final RuleMetadata target ) { RuleMetadata metaData = getMetaData ( target . getAttributeName ( ) ) ; if ( metaData != null ) { metaData . setValue ( target . getValue ( ) ) ; return true ; } addMetadata ( target ) ; return false ; }
Update metaData element if it exists or add it otherwise
7,884
public boolean hasDSLSentences ( ) { if ( this . lhs != null ) { for ( IPattern pattern : this . lhs ) { if ( pattern instanceof DSLSentence ) { return true ; } } } if ( this . rhs != null ) { for ( IAction action : this . rhs ) { if ( action instanceof DSLSentence ) { return true ; } } } return false ; }
Returns true if any DSLSentences are used .
7,885
public DTCellValue52 cloneDefaultValueCell ( ) { DTCellValue52 cloned = new DTCellValue52 ( ) ; cloned . valueBoolean = valueBoolean ; cloned . valueDate = valueDate ; cloned . valueNumeric = valueNumeric ; cloned . valueString = valueString ; cloned . dataType = dataType ; return cloned ; }
Clones this default value instance .
7,886
public WindowMemory createMemory ( final RuleBaseConfiguration config , InternalWorkingMemory wm ) { WindowMemory memory = new WindowMemory ( ) ; memory . behaviorContext = this . behavior . createBehaviorContext ( ) ; return memory ; }
Creates the WindowNode s memory .
7,887
private void moveRowsBasedOnPriority ( ) { for ( RowNumber myNumber : overs . keySet ( ) ) { Over over = overs . get ( myNumber ) ; int newIndex = rowOrder . indexOf ( new RowNumber ( over . getOver ( ) ) ) ; rowOrder . remove ( myNumber ) ; rowOrder . add ( newIndex , myNumber ) ; } }
Move rows on top of the row it has priority over .
7,888
private void initOpenMBeanInfo ( ) { OpenMBeanAttributeInfoSupport [ ] attributes = new OpenMBeanAttributeInfoSupport [ 4 ] ; OpenMBeanConstructorInfoSupport [ ] constructors = new OpenMBeanConstructorInfoSupport [ 1 ] ; OpenMBeanOperationInfoSupport [ ] operations = new OpenMBeanOperationInfoSupport [ 2 ] ; MBeanNotificationInfo [ ] notifications = new MBeanNotificationInfo [ 0 ] ; try { attributes [ 0 ] = new OpenMBeanAttributeInfoSupport ( ATTR_ID , "Knowledge Base Id" , SimpleType . STRING , true , false , false ) ; attributes [ 1 ] = new OpenMBeanAttributeInfoSupport ( ATTR_SESSION_COUNT , "Number of created sessions for this Knowledge Base" , SimpleType . LONG , true , false , false ) ; attributes [ 2 ] = new OpenMBeanAttributeInfoSupport ( ATTR_GLOBALS , "List of globals" , globalsTableType , true , false , false ) ; attributes [ 3 ] = new OpenMBeanAttributeInfoSupport ( ATTR_PACKAGES , "List of Packages" , new ArrayType ( 1 , SimpleType . STRING ) , true , false , false ) ; constructors [ 0 ] = new OpenMBeanConstructorInfoSupport ( "KnowledgeBaseMonitoringMXBean" , "Constructs a KnowledgeBaseMonitoringMXBean instance." , new OpenMBeanParameterInfoSupport [ 0 ] ) ; OpenMBeanParameterInfo [ ] params = new OpenMBeanParameterInfoSupport [ 0 ] ; operations [ 0 ] = new OpenMBeanOperationInfoSupport ( OP_START_INTERNAL_MBEANS , "Creates, registers and starts all the dependent MBeans that allow monitor all the details in this KnowledgeBase." , params , SimpleType . VOID , MBeanOperationInfo . INFO ) ; operations [ 1 ] = new OpenMBeanOperationInfoSupport ( OP_STOP_INTERNAL_MBEANS , "Stops and disposes all the dependent MBeans that allow monitor all the details in this KnowledgeBase." , params , SimpleType . VOID , MBeanOperationInfo . INFO ) ; info = new OpenMBeanInfoSupport ( this . getClass ( ) . getName ( ) , "Knowledge Base Monitor MXBean" , attributes , constructors , operations , notifications ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Initialize the open mbean metadata
7,889
public String interpolate ( ) { getValues ( ) ; if ( definition == null ) { return "" ; } int variableStart = definition . indexOf ( "{" ) ; if ( variableStart < 0 ) { return definition ; } int index = 0 ; int variableEnd = 0 ; StringBuilder sb = new StringBuilder ( ) ; while ( variableStart >= 0 ) { sb . append ( definition . substring ( variableEnd , variableStart ) ) ; variableEnd = getIndexForEndOfVariable ( definition , variableStart ) + 1 ; variableStart = definition . indexOf ( "{" , variableEnd ) ; sb . append ( values . get ( index ++ ) . getValue ( ) ) ; } if ( variableEnd < definition . length ( ) ) { sb . append ( definition . substring ( variableEnd ) ) ; } return sb . toString ( ) ; }
This will strip off any { stuff substituting values accordingly
7,890
public DSLSentence copy ( ) { final DSLSentence copy = new DSLSentence ( ) ; copy . drl = getDrl ( ) ; copy . definition = getDefinition ( ) ; copy . values = mapCopy ( getValues ( ) ) ; return copy ; }
This is used by the GUI when adding a sentence to LHS or RHS .
7,891
private void parseSentence ( ) { if ( sentence == null ) { return ; } definition = sentence ; values = new ArrayList < DSLVariableValue > ( ) ; sentence = null ; int variableStart = definition . indexOf ( "{" ) ; while ( variableStart >= 0 ) { int variableEnd = getIndexForEndOfVariable ( definition , variableStart ) ; String variable = definition . substring ( variableStart + 1 , variableEnd ) ; values . add ( parseValue ( variable ) ) ; variableStart = definition . indexOf ( "{" , variableEnd ) ; } }
to differentiate value from data - type from restriction
7,892
private void parseDefinition ( ) { values = new ArrayList < DSLVariableValue > ( ) ; if ( getDefinition ( ) == null ) { return ; } int variableStart = definition . indexOf ( "{" ) ; while ( variableStart >= 0 ) { int variableEnd = getIndexForEndOfVariable ( definition , variableStart ) ; String variable = definition . substring ( variableStart + 1 , variableEnd ) ; values . add ( parseValue ( variable ) ) ; variableStart = definition . indexOf ( "{" , variableEnd ) ; } }
Build the Values from the Definition .
7,893
private void addPackage ( Resource resource ) throws DroolsParserException , IOException { if ( pmmlCompiler != null ) { if ( pmmlCompiler . getResults ( ) . isEmpty ( ) ) { addPMMLPojos ( pmmlCompiler , resource ) ; if ( pmmlCompiler . getResults ( ) . isEmpty ( ) ) { List < PackageDescr > packages = getPackageDescrs ( resource ) ; if ( packages != null && ! packages . isEmpty ( ) ) { for ( PackageDescr descr : packages ) { this . kbuilder . addPackage ( descr ) ; } } } } } }
This method does the work of calling the PMML compiler and then assembling the results into packages that are added to the KnowledgeBuilder
7,894
private List < PackageDescr > getPackageDescrs ( Resource resource ) throws DroolsParserException , IOException { List < PMMLResource > resources = pmmlCompiler . precompile ( resource . getInputStream ( ) , null , null ) ; if ( resources != null && ! resources . isEmpty ( ) ) { return generatedResourcesToPackageDescr ( resource , resources ) ; } return null ; }
This method calls the PMML compiler to get PMMLResource objects which are used to create one or more PackageDescr objects
7,895
private RuleModel updateMethodCall ( RuleModel model ) { for ( int i = 0 ; i < model . rhs . length ; i ++ ) { if ( model . rhs [ i ] instanceof ActionCallMethod ) { ActionCallMethod action = ( ActionCallMethod ) model . rhs [ i ] ; if ( action . getMethodName ( ) == null || "" . equals ( action . getMethodName ( ) ) ) { if ( action . getFieldValues ( ) != null && action . getFieldValues ( ) . length >= 1 ) { action . setMethodName ( action . getFieldValues ( ) [ 0 ] . getField ( ) ) ; action . setFieldValues ( new ActionFieldValue [ 0 ] ) ; action . setState ( ActionCallMethod . TYPE_DEFINED ) ; } } } } return model ; }
before that needs to be updated .
7,896
private static boolean isValidChar ( char c ) { if ( c >= '0' && c <= '9' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' ) { return true ; } return c != ' ' && c != '\u00A0' && ! Character . isWhitespace ( c ) && ! Character . isWhitespace ( c ) ; }
This method defines what characters are valid for the output of normalizeVariableName . Spaces and control characters are invalid . There is a fast - path for well known characters
7,897
public static Method getGenericAccessor ( Class < ? > clazz , String field ) { LOG . trace ( "getGenericAccessor({}, {})" , clazz , field ) ; String accessorQualifiedName = new StringBuilder ( clazz . getCanonicalName ( ) ) . append ( "." ) . append ( field ) . toString ( ) ; return accessorCache . computeIfAbsent ( accessorQualifiedName , key -> Stream . of ( clazz . getMethods ( ) ) . filter ( m -> Optional . ofNullable ( m . getAnnotation ( FEELProperty . class ) ) . map ( ann -> ann . value ( ) . equals ( field ) ) . orElse ( false ) ) . findFirst ( ) . orElse ( getAccessor ( clazz , field ) ) ) ; }
FEEL annotated or else Java accessor .
7,898
public static Method getAccessor ( Class < ? > clazz , String field ) { LOG . trace ( "getAccessor({}, {})" , clazz , field ) ; try { return clazz . getMethod ( "get" + ucFirst ( field ) ) ; } catch ( NoSuchMethodException e ) { try { return clazz . getMethod ( field ) ; } catch ( NoSuchMethodException e1 ) { try { return clazz . getMethod ( "is" + ucFirst ( field ) ) ; } catch ( NoSuchMethodException e2 ) { return null ; } } } }
JavaBean - spec compliant accessor .
7,899
public static Boolean isEqual ( Object left , Object right , EvaluationContext ctx ) { if ( left == null || right == null ) { return left == right ; } if ( left instanceof Collection && ! ( right instanceof Collection ) && ( ( Collection ) left ) . size ( ) == 1 ) { left = ( ( Collection ) left ) . toArray ( ) [ 0 ] ; } else if ( right instanceof Collection && ! ( left instanceof Collection ) && ( ( Collection ) right ) . size ( ) == 1 ) { right = ( ( Collection ) right ) . toArray ( ) [ 0 ] ; } if ( left instanceof Range && right instanceof Range ) { return isEqual ( ( Range ) left , ( Range ) right ) ; } else if ( left instanceof Iterable && right instanceof Iterable ) { return isEqual ( ( Iterable ) left , ( Iterable ) right ) ; } else if ( left instanceof Map && right instanceof Map ) { return isEqual ( ( Map ) left , ( Map ) right ) ; } else if ( left instanceof TemporalAccessor && right instanceof TemporalAccessor ) { if ( BuiltInType . determineTypeFromInstance ( left ) == BuiltInType . TIME && BuiltInType . determineTypeFromInstance ( right ) == BuiltInType . TIME ) { return isEqualTime ( ( TemporalAccessor ) left , ( TemporalAccessor ) right ) ; } else if ( BuiltInType . determineTypeFromInstance ( left ) == BuiltInType . DATE_TIME && BuiltInType . determineTypeFromInstance ( right ) == BuiltInType . DATE_TIME ) { return isEqualDateTime ( ( TemporalAccessor ) left , ( TemporalAccessor ) right ) ; } } return compare ( left , right , ctx , ( l , r ) -> l . compareTo ( r ) == 0 ) ; }
Compares left and right for equality applying FEEL semantics to specific data types