idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
7,700
public Elements getElementsByAttributeValue ( String key , String value ) { return Collector . collect ( new Evaluator . AttributeWithValue ( key , value ) , this ) ; }
Find elements that have an attribute with the specific value . Case insensitive .
7,701
public Elements getElementsByAttributeValueNot ( String key , String value ) { return Collector . collect ( new Evaluator . AttributeWithValueNot ( key , value ) , this ) ; }
Find elements that either do not have this attribute or have it with a different value . Case insensitive .
7,702
public Elements getElementsByAttributeValueStarting ( String key , String valuePrefix ) { return Collector . collect ( new Evaluator . AttributeWithValueStarting ( key , valuePrefix ) , this ) ; }
Find elements that have attributes that start with the value prefix . Case insensitive .
7,703
public Elements getElementsByAttributeValueEnding ( String key , String valueSuffix ) { return Collector . collect ( new Evaluator . AttributeWithValueEnding ( key , valueSuffix ) , this ) ; }
Find elements that have attributes that end with the value suffix . Case insensitive .
7,704
public Elements getElementsByAttributeValueContaining ( String key , String match ) { return Collector . collect ( new Evaluator . AttributeWithValueContaining ( key , match ) , this ) ; }
Find elements that have attributes whose value contains the match string . Case insensitive .
7,705
public Elements getElementsMatchingText ( String regex ) { Pattern pattern ; try { pattern = Pattern . compile ( regex ) ; } catch ( PatternSyntaxException e ) { throw new IllegalArgumentException ( "Pattern syntax error: " + regex , e ) ; } return getElementsMatchingText ( pattern ) ; }
Find elements whose text matches the supplied regular expression .
7,706
public static ConstrainableInputStream wrap ( InputStream in , int bufferSize , int maxSize ) { return in instanceof ConstrainableInputStream ? ( ConstrainableInputStream ) in : new ConstrainableInputStream ( in , bufferSize , maxSize ) ; }
If this InputStream is not already a ConstrainableInputStream let it be one .
7,707
public ByteBuffer readToByteBuffer ( int max ) throws IOException { Validate . isTrue ( max >= 0 , "maxSize must be 0 (unlimited) or larger" ) ; final boolean localCapped = max > 0 ; final int bufferSize = localCapped && max < DefaultSize ? max : DefaultSize ; final byte [ ] readBuffer = new byte [ bufferSize ] ; final ByteArrayOutputStream outStream = new ByteArrayOutputStream ( bufferSize ) ; int read ; int remaining = max ; while ( true ) { read = read ( readBuffer ) ; if ( read == - 1 ) break ; if ( localCapped ) { if ( read >= remaining ) { outStream . write ( readBuffer , 0 , remaining ) ; break ; } remaining -= read ; } outStream . write ( readBuffer , 0 , read ) ; } return ByteBuffer . wrap ( outStream . toByteArray ( ) ) ; }
Reads this inputstream to a ByteBuffer . The supplied max may be less than the inputstream s max to support reading just the first bytes .
7,708
void popStackToClose ( String ... elNames ) { for ( int pos = stack . size ( ) - 1 ; pos >= 0 ; pos -- ) { Element next = stack . get ( pos ) ; stack . remove ( pos ) ; if ( inSorted ( next . normalName ( ) , elNames ) ) break ; } }
elnames is sorted comes from Constants
7,709
void pushActiveFormattingElements ( Element in ) { int numSeen = 0 ; for ( int pos = formattingElements . size ( ) - 1 ; pos >= 0 ; pos -- ) { Element el = formattingElements . get ( pos ) ; if ( el == null ) break ; if ( isSameFormattingElement ( in , el ) ) numSeen ++ ; if ( numSeen == 3 ) { formattingElements . remove ( pos ) ; break ; } } formattingElements . add ( in ) ; }
active formatting elements
7,710
private void checkCapacity ( int minNewSize ) { Validate . isTrue ( minNewSize >= size ) ; int curSize = keys . length ; if ( curSize >= minNewSize ) return ; int newSize = curSize >= InitialCapacity ? size * GrowthFactor : InitialCapacity ; if ( minNewSize > newSize ) newSize = minNewSize ; keys = copyOf ( keys , newSize ) ; vals = copyOf ( vals , newSize ) ; }
check there s room for more
7,711
private static String [ ] copyOf ( String [ ] orig , int size ) { final String [ ] copy = new String [ size ] ; System . arraycopy ( orig , 0 , copy , 0 , Math . min ( orig . length , size ) ) ; return copy ; }
simple implementation of Arrays . copy for support of Android API 8 .
7,712
public String get ( String key ) { int i = indexOfKey ( key ) ; return i == NotFound ? EmptyString : checkNotNull ( vals [ i ] ) ; }
Get an attribute value by key .
7,713
public String getIgnoreCase ( String key ) { int i = indexOfKeyIgnoreCase ( key ) ; return i == NotFound ? EmptyString : checkNotNull ( vals [ i ] ) ; }
Get an attribute s value by case - insensitive key
7,714
private void add ( String key , String value ) { checkCapacity ( size + 1 ) ; keys [ size ] = key ; vals [ size ] = value ; size ++ ; }
adds without checking if this key exists
7,715
public Attributes put ( String key , boolean value ) { if ( value ) putIgnoreCase ( key , null ) ; else remove ( key ) ; return this ; }
Set a new boolean attribute remove attribute if value is false .
7,716
private void remove ( int index ) { Validate . isFalse ( index >= size ) ; int shifted = size - index - 1 ; if ( shifted > 0 ) { System . arraycopy ( keys , index + 1 , keys , index , shifted ) ; System . arraycopy ( vals , index + 1 , vals , index , shifted ) ; } size -- ; keys [ size ] = null ; vals [ size ] = null ; }
removes and shifts up
7,717
public void addAll ( Attributes incoming ) { if ( incoming . size ( ) == 0 ) return ; checkCapacity ( size + incoming . size ) ; for ( Attribute attr : incoming ) { put ( attr ) ; } }
Add all the attributes from the incoming set to this set .
7,718
public List < Attribute > asList ( ) { ArrayList < Attribute > list = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { Attribute attr = vals [ i ] == null ? new BooleanAttribute ( keys [ i ] ) : new Attribute ( keys [ i ] , vals [ i ] , Attributes . this ) ; list . add ( attr ) ; } return Collections . unmodifiableList ( list ) ; }
Get the attributes as a List for iteration .
7,719
public String html ( ) { StringBuilder sb = StringUtil . borrowBuilder ( ) ; try { html ( sb , ( new Document ( "" ) ) . outputSettings ( ) ) ; } catch ( IOException e ) { throw new SerializationException ( e ) ; } return StringUtil . releaseBuilder ( sb ) ; }
Get the HTML representation of these attributes .
7,720
public void normalize ( ) { for ( int i = 0 ; i < size ; i ++ ) { keys [ i ] = lowerCase ( keys [ i ] ) ; } }
Internal method . Lowercases all keys .
7,721
public TextNode splitText ( int offset ) { final String text = coreValue ( ) ; Validate . isTrue ( offset >= 0 , "Split offset must be not be negative" ) ; Validate . isTrue ( offset < text . length ( ) , "Split offset must not be greater than current text length" ) ; String head = text . substring ( 0 , offset ) ; String tail = text . substring ( offset ) ; text ( head ) ; TextNode tailNode = new TextNode ( tail ) ; if ( parent ( ) != null ) parent ( ) . addChildren ( siblingIndex ( ) + 1 , tailNode ) ; return tailNode ; }
Split this text node into two nodes at the specified string offset . After splitting this node will contain the original text up to the offset and will have a new text node sibling containing the text after the offset .
7,722
public boolean matches ( String seq ) { return queue . regionMatches ( true , pos , seq , 0 , seq . length ( ) ) ; }
Tests if the next characters on the queue match the sequence . Case insensitive .
7,723
public boolean matchesAny ( String ... seq ) { for ( String s : seq ) { if ( matches ( s ) ) return true ; } return false ; }
Tests if the next characters match any of the sequences . Case insensitive .
7,724
public String consumeTo ( String seq ) { int offset = queue . indexOf ( seq , pos ) ; if ( offset != - 1 ) { String consumed = queue . substring ( pos , offset ) ; pos += consumed . length ( ) ; return consumed ; } else { return remainder ( ) ; } }
Pulls a string off the queue up to but exclusive of the match sequence or to the queue running out .
7,725
public static String unescape ( String in ) { StringBuilder out = StringUtil . borrowBuilder ( ) ; char last = 0 ; for ( char c : in . toCharArray ( ) ) { if ( c == ESC ) { if ( last != 0 && last == ESC ) out . append ( c ) ; } else out . append ( c ) ; last = c ; } return StringUtil . releaseBuilder ( out ) ; }
Unescape a \ escaped string .
7,726
public String getWholeDeclaration ( ) { StringBuilder sb = StringUtil . borrowBuilder ( ) ; try { getWholeDeclaration ( sb , new Document . OutputSettings ( ) ) ; } catch ( IOException e ) { throw new SerializationException ( e ) ; } return StringUtil . releaseBuilder ( sb ) . trim ( ) ; }
Get the unencoded XML declaration .
7,727
public String normalizeTag ( String name ) { name = name . trim ( ) ; if ( ! preserveTagCase ) name = lowerCase ( name ) ; return name ; }
Normalizes a tag name according to the case preservation setting .
7,728
public String normalizeAttribute ( String name ) { name = name . trim ( ) ; if ( ! preserveAttributeCase ) name = lowerCase ( name ) ; return name ; }
Normalizes an attribute according to the case preservation setting .
7,729
public Parser setTrackErrors ( int maxErrors ) { errors = maxErrors > 0 ? ParseErrorList . tracking ( maxErrors ) : ParseErrorList . noTracking ( ) ; return this ; }
Enable or disable parse error tracking for the next parse .
7,730
public static Document parse ( String html , String baseUri ) { TreeBuilder treeBuilder = new HtmlTreeBuilder ( ) ; return treeBuilder . parse ( new StringReader ( html ) , baseUri , new Parser ( treeBuilder ) ) ; }
Parse HTML into a Document .
7,731
public static List < Node > parseXmlFragment ( String fragmentXml , String baseUri ) { XmlTreeBuilder treeBuilder = new XmlTreeBuilder ( ) ; return treeBuilder . parseFragment ( fragmentXml , baseUri , new Parser ( treeBuilder ) ) ; }
Parse a fragment of XML into a list of nodes .
7,732
public static String unescapeEntities ( String string , boolean inAttribute ) { Tokeniser tokeniser = new Tokeniser ( new CharacterReader ( string ) , ParseErrorList . noTracking ( ) ) ; return tokeniser . unescapeEntities ( inAttribute ) ; }
Utility method to unescape HTML entities from a string
7,733
String unescapeEntities ( boolean inAttribute ) { StringBuilder builder = StringUtil . borrowBuilder ( ) ; while ( ! reader . isEmpty ( ) ) { builder . append ( reader . consumeTo ( '&' ) ) ; if ( reader . matches ( '&' ) ) { reader . consume ( ) ; int [ ] c = consumeCharacterReference ( null , inAttribute ) ; if ( c == null || c . length == 0 ) builder . append ( '&' ) ; else { builder . appendCodePoint ( c [ 0 ] ) ; if ( c . length == 2 ) builder . appendCodePoint ( c [ 1 ] ) ; } } } return StringUtil . releaseBuilder ( builder ) ; }
Utility method to consume reader and unescape entities found within .
7,734
public String getPlainText ( Element element ) { FormattingVisitor formatter = new FormattingVisitor ( ) ; NodeTraversor . traverse ( formatter , element ) ; return formatter . toString ( ) ; }
Format an Element to plain - text
7,735
public boolean isXmlDeclaration ( ) { String data = getData ( ) ; return ( data . length ( ) > 1 && ( data . startsWith ( "!" ) || data . startsWith ( "?" ) ) ) ; }
Check if this comment looks like an XML Declaration .
7,736
public XmlDeclaration asXmlDeclaration ( ) { String data = getData ( ) ; Document doc = Jsoup . parse ( "<" + data . substring ( 1 , data . length ( ) - 1 ) + ">" , baseUri ( ) , Parser . xmlParser ( ) ) ; XmlDeclaration decl = null ; if ( doc . children ( ) . size ( ) > 0 ) { Element el = doc . child ( 0 ) ; decl = new XmlDeclaration ( NodeUtils . parser ( doc ) . settings ( ) . normalizeTag ( el . tagName ( ) ) , data . startsWith ( "!" ) ) ; decl . attributes ( ) . addAll ( el . attributes ( ) ) ; } return decl ; }
Attempt to cast this comment to an XML Declaration note .
7,737
public static Evaluator parse ( String query ) { try { QueryParser p = new QueryParser ( query ) ; return p . parse ( ) ; } catch ( IllegalArgumentException e ) { throw new Selector . SelectorParseException ( e . getMessage ( ) ) ; } }
Parse a CSS query into an Evaluator .
7,738
Evaluator parse ( ) { tq . consumeWhitespace ( ) ; if ( tq . matchesAny ( combinators ) ) { evals . add ( new StructuralEvaluator . Root ( ) ) ; combinator ( tq . consume ( ) ) ; } else { findElements ( ) ; } while ( ! tq . isEmpty ( ) ) { boolean seenWhite = tq . consumeWhitespace ( ) ; if ( tq . matchesAny ( combinators ) ) { combinator ( tq . consume ( ) ) ; } else if ( seenWhite ) { combinator ( ' ' ) ; } else { findElements ( ) ; } } if ( evals . size ( ) == 1 ) return evals . get ( 0 ) ; return new CombiningEvaluator . And ( evals ) ; }
Parse the query
7,739
static Parser parser ( Node node ) { Document doc = node . ownerDocument ( ) ; return doc != null && doc . parser ( ) != null ? doc . parser ( ) : new Parser ( new HtmlTreeBuilder ( ) ) ; }
Get the parser that was used to make this node or the default HTML parser if it has no parent .
7,740
public static Element selectFirst ( String cssQuery , Element root ) { Validate . notEmpty ( cssQuery ) ; return Collector . findFirst ( QueryParser . parse ( cssQuery ) , root ) ; }
Find the first element that matches the query .
7,741
protected final boolean exec ( ) { Object backup = replay ( captured ) ; try { result = compute ( ) ; return true ; } finally { restore ( backup ) ; } }
Implements execution conventions for RecursiveTask .
7,742
public static Operator getReversedOperator ( Operator e ) { if ( e . equals ( Operator . NOT_EQUAL ) ) { return Operator . EQUAL ; } else if ( e . equals ( Operator . EQUAL ) ) { return Operator . NOT_EQUAL ; } else if ( e . equals ( Operator . GREATER ) ) { return Operator . LESS_OR_EQUAL ; } else if ( e . equals ( Operator . LESS ) ) { return Operator . GREATER_OR_EQUAL ; } else if ( e . equals ( Operator . GREATER_OR_EQUAL ) ) { return Operator . LESS ; } else if ( e . equals ( Operator . LESS_OR_EQUAL ) ) { return Operator . GREATER ; } else { return Operator . determineOperator ( e . getOperatorString ( ) , ! e . isNegated ( ) ) ; } }
Takes the given operator e and returns a reversed version of it .
7,743
private String addRow ( String rowId , String [ ] row ) { Map < InterpolationVariable , Integer > vars = getInterpolationVariables ( ) ; if ( row . length != vars . size ( ) - 1 ) { throw new IllegalArgumentException ( "Invalid numbers of columns: " + row . length + " expected: " + ( vars . size ( ) - 1 ) ) ; } if ( rowId == null || rowId . length ( ) == 0 ) { rowId = getNewIdColValue ( ) ; } for ( Map . Entry < InterpolationVariable , Integer > entry : vars . entrySet ( ) ) { List < String > list = table . get ( entry . getKey ( ) . getVarName ( ) ) ; if ( list == null ) { list = new ArrayList < String > ( ) ; table . put ( entry . getKey ( ) . getVarName ( ) , list ) ; } if ( rowsCount != list . size ( ) ) { throw new IllegalArgumentException ( "invalid list size for " + entry . getKey ( ) + ", expected: " + rowsCount + " was: " + list . size ( ) ) ; } if ( ID_COLUMN_NAME . equals ( entry . getKey ( ) . getVarName ( ) ) ) { list . add ( rowId ) ; } else { list . add ( row [ entry . getValue ( ) ] ) ; } } rowsCount ++ ; return rowId ; }
Append a row of data
7,744
public void addPackageFromDrl ( final Reader reader ) throws DroolsParserException , IOException { addPackageFromDrl ( reader , new ReaderResource ( reader , ResourceType . DRL ) ) ; }
Load a rule package from DRL source .
7,745
public void addPackageFromDrl ( final Reader reader , final Resource sourceResource ) throws DroolsParserException , IOException { this . resource = sourceResource ; final DrlParser parser = new DrlParser ( configuration . getLanguageLevel ( ) ) ; final PackageDescr pkg = parser . parse ( sourceResource , reader ) ; this . results . addAll ( parser . getErrors ( ) ) ; if ( pkg == null ) { addBuilderResult ( new ParserError ( sourceResource , "Parser returned a null Package" , 0 , 0 ) ) ; } if ( ! parser . hasErrors ( ) ) { addPackage ( pkg ) ; } this . resource = null ; }
Load a rule package from DRL source and associate all loaded artifacts with the given resource .
7,746
public void addPackageFromXml ( final Reader reader ) throws DroolsParserException , IOException { this . resource = new ReaderResource ( reader , ResourceType . XDRL ) ; final XmlPackageReader xmlReader = new XmlPackageReader ( this . configuration . getSemanticModules ( ) ) ; xmlReader . getParser ( ) . setClassLoader ( this . rootClassLoader ) ; try { xmlReader . read ( reader ) ; } catch ( final SAXException e ) { throw new DroolsParserException ( e . toString ( ) , e . getCause ( ) ) ; } addPackage ( xmlReader . getPackageDescr ( ) ) ; this . resource = null ; }
Load a rule package from XML source .
7,747
public void addPackageFromDrl ( final Reader source , final Reader dsl ) throws DroolsParserException , IOException { this . resource = new ReaderResource ( source , ResourceType . DSLR ) ; final DrlParser parser = new DrlParser ( configuration . getLanguageLevel ( ) ) ; final PackageDescr pkg = parser . parse ( source , dsl ) ; this . results . addAll ( parser . getErrors ( ) ) ; if ( ! parser . hasErrors ( ) ) { addPackage ( pkg ) ; } this . resource = null ; }
Load a rule package from DRL source using the supplied DSL configuration .
7,748
private void inheritPackageAttributes ( Map < String , AttributeDescr > pkgAttributes , RuleDescr ruleDescr ) { if ( pkgAttributes == null ) { return ; } for ( AttributeDescr attrDescr : pkgAttributes . values ( ) ) { ruleDescr . getAttributes ( ) . putIfAbsent ( attrDescr . getName ( ) , attrDescr ) ; } }
Entity rules inherit package attributes
7,749
private GenericKieSessionMonitoringImpl getKnowledgeSessionBean ( CBSKey cbsKey , KieRuntimeEventManager ksession ) { if ( mbeansRefs . get ( cbsKey ) != null ) { return ( GenericKieSessionMonitoringImpl ) mbeansRefs . get ( cbsKey ) ; } else { if ( ksession instanceof StatelessKnowledgeSession ) { synchronized ( mbeansRefs ) { if ( mbeansRefs . get ( cbsKey ) != null ) { return ( GenericKieSessionMonitoringImpl ) mbeansRefs . get ( cbsKey ) ; } else { try { StatelessKieSessionMonitoringImpl mbean = new StatelessKieSessionMonitoringImpl ( cbsKey . kcontainerId , cbsKey . kbaseId , cbsKey . ksessionName ) ; registerMBean ( cbsKey , mbean , mbean . getName ( ) ) ; mbeansRefs . put ( cbsKey , mbean ) ; return mbean ; } catch ( Exception e ) { logger . error ( "Unable to instantiate and register StatelessKieSessionMonitoringMBean" ) ; } return null ; } } } else { synchronized ( mbeansRefs ) { if ( mbeansRefs . get ( cbsKey ) != null ) { return ( GenericKieSessionMonitoringImpl ) mbeansRefs . get ( cbsKey ) ; } else { try { KieSessionMonitoringImpl mbean = new KieSessionMonitoringImpl ( cbsKey . kcontainerId , cbsKey . kbaseId , cbsKey . ksessionName ) ; registerMBean ( cbsKey , mbean , mbean . getName ( ) ) ; mbeansRefs . put ( cbsKey , mbean ) ; return mbean ; } catch ( Exception e ) { logger . error ( "Unable to instantiate and register (stateful) KieSessionMonitoringMBean" ) ; } return null ; } } } } }
Get currently registered session monitor eventually creating it if necessary .
7,750
private BranchTuples getBranchTuples ( LeftTupleSink sink , LeftTuple leftTuple ) { BranchTuples branchTuples = new BranchTuples ( ) ; LeftTuple child = leftTuple . getFirstChild ( ) ; if ( child != null ) { if ( child . getTupleSink ( ) == sink ) { branchTuples . mainLeftTuple = child ; } else { branchTuples . rtnLeftTuple = child ; } child = child . getHandleNext ( ) ; if ( child != null ) { if ( child . getTupleSink ( ) == sink ) { branchTuples . mainLeftTuple = child ; } else { branchTuples . rtnLeftTuple = child ; } } } return branchTuples ; }
A branch has two potential sinks . rtnSink is for the sink if the contained logic returns true . mainSink is for propagations after the branch node if they are allowed . it may have one or the other or both . there is no state that indicates whether one or the other or both are present so all tuple children must be inspected and references coalesced from that . when handling updates and deletes it must search the child tuples to colasce the references . This is done by checking the tuple sink with the known main or rtn sink .
7,751
protected ClassWriter buildClassHeader ( ClassLoader classLoader , ClassDefinition classDef ) { boolean reactive = classDef . isReactive ( ) ; String [ ] original = classDef . getInterfaces ( ) ; int interfacesNr = original . length + ( reactive ? 2 : 1 ) ; String [ ] interfaces = new String [ interfacesNr ] ; for ( int i = 0 ; i < original . length ; i ++ ) { interfaces [ i ] = BuildUtils . getInternalType ( original [ i ] ) ; } interfaces [ original . length ] = BuildUtils . getInternalType ( GeneratedFact . class . getName ( ) ) ; if ( reactive ) { interfaces [ original . length + 1 ] = BuildUtils . getInternalType ( ReactiveObject . class . getName ( ) ) ; } int classModifiers = Opcodes . ACC_PUBLIC + Opcodes . ACC_SUPER ; if ( classDef . isAbstrakt ( ) ) { classModifiers += Opcodes . ACC_ABSTRACT ; } ClassWriter cw = createClassWriter ( classLoader , classModifiers , BuildUtils . getInternalType ( classDef . getClassName ( ) ) , null , BuildUtils . getInternalType ( classDef . getSuperClass ( ) ) , interfaces ) ; buildClassAnnotations ( classDef , cw ) ; cw . visitSource ( classDef . getClassName ( ) + ".java" , null ) ; return cw ; }
Defines the class header for the given class definition
7,752
protected void buildField ( ClassVisitor cw , FieldDefinition fieldDef ) { FieldVisitor fv = cw . visitField ( Opcodes . ACC_PROTECTED , fieldDef . getName ( ) , BuildUtils . getTypeDescriptor ( fieldDef . getTypeName ( ) ) , null , null ) ; buildFieldAnnotations ( fieldDef , fv ) ; fv . visitEnd ( ) ; }
Creates the field defined by the given FieldDefinition
7,753
protected void buildDefaultConstructor ( ClassVisitor cw , ClassDefinition classDef ) { MethodVisitor mv = cw . visitMethod ( Opcodes . ACC_PUBLIC , "<init>" , Type . getMethodDescriptor ( Type . VOID_TYPE , new Type [ ] { } ) , null , null ) ; mv . visitCode ( ) ; Label l0 = null ; if ( this . debug ) { l0 = new Label ( ) ; mv . visitLabel ( l0 ) ; } boolean hasObjects = defaultConstructorStart ( mv , classDef ) ; mv . visitInsn ( Opcodes . RETURN ) ; Label l1 = null ; if ( this . debug ) { l1 = new Label ( ) ; mv . visitLabel ( l1 ) ; mv . visitLocalVariable ( "this" , BuildUtils . getTypeDescriptor ( classDef . getClassName ( ) ) , null , l0 , l1 , 0 ) ; } mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; }
Creates a default constructor for the class
7,754
protected void initializeDynamicTypeStructures ( MethodVisitor mv , ClassDefinition classDef ) { if ( classDef . isFullTraiting ( ) ) { mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitTypeInsn ( NEW , Type . getInternalName ( TraitFieldTMSImpl . class ) ) ; mv . visitInsn ( DUP ) ; mv . visitMethodInsn ( INVOKESPECIAL , Type . getInternalName ( TraitFieldTMSImpl . class ) , "<init>" , "()V" ) ; mv . visitFieldInsn ( PUTFIELD , BuildUtils . getInternalType ( classDef . getClassName ( ) ) , TraitableBean . FIELDTMS_FIELD_NAME , Type . getDescriptor ( TraitFieldTMS . class ) ) ; for ( FactField hardField : classDef . getFields ( ) ) { FieldDefinition fld = ( FieldDefinition ) hardField ; mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitFieldInsn ( GETFIELD , BuildUtils . getInternalType ( classDef . getClassName ( ) ) , TraitableBean . FIELDTMS_FIELD_NAME , Type . getDescriptor ( TraitFieldTMS . class ) ) ; mv . visitLdcInsn ( Type . getType ( BuildUtils . getTypeDescriptor ( classDef . getClassName ( ) ) ) ) ; mv . visitLdcInsn ( fld . resolveAlias ( ) ) ; if ( BuildUtils . isPrimitive ( fld . getTypeName ( ) ) ) { mv . visitLdcInsn ( Type . getType ( BuildUtils . getTypeDescriptor ( BuildUtils . box ( fld . getTypeName ( ) ) ) ) ) ; } else { mv . visitLdcInsn ( Type . getType ( BuildUtils . getTypeDescriptor ( fld . getTypeName ( ) ) ) ) ; } mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , BuildUtils . getInternalType ( classDef . getClassName ( ) ) , BuildUtils . getterName ( fld . getName ( ) , fld . getTypeName ( ) ) , "()" + BuildUtils . getTypeDescriptor ( fld . getTypeName ( ) ) ) ; if ( BuildUtils . isPrimitive ( fld . getTypeName ( ) ) ) { mv . visitMethodInsn ( INVOKESTATIC , BuildUtils . getInternalType ( BuildUtils . box ( fld . getTypeName ( ) ) ) , "valueOf" , "(" + BuildUtils . getTypeDescriptor ( fld . getTypeName ( ) ) + ")" + BuildUtils . getTypeDescriptor ( BuildUtils . box ( fld . getTypeName ( ) ) ) ) ; } if ( fld . getInitExpr ( ) != null ) { mv . visitLdcInsn ( fld . getInitExpr ( ) ) ; } else { mv . visitInsn ( ACONST_NULL ) ; } mv . visitMethodInsn ( INVOKEINTERFACE , Type . getInternalName ( TraitFieldTMS . class ) , "registerField" , Type . getMethodDescriptor ( Type . VOID_TYPE , new Type [ ] { Type . getType ( Class . class ) , Type . getType ( String . class ) , Type . getType ( Class . class ) , Type . getType ( Object . class ) , Type . getType ( String . class ) } ) ) ; } } }
Initializes the trait map and dynamic property map to empty values
7,755
protected void buildConstructorWithFields ( ClassVisitor cw , ClassDefinition classDef , Collection < FieldDefinition > fieldDefs ) { Type [ ] params = new Type [ fieldDefs . size ( ) ] ; int index = 0 ; for ( FieldDefinition field : fieldDefs ) { params [ index ++ ] = Type . getType ( BuildUtils . getTypeDescriptor ( field . getTypeName ( ) ) ) ; } MethodVisitor mv = cw . visitMethod ( Opcodes . ACC_PUBLIC , "<init>" , Type . getMethodDescriptor ( Type . VOID_TYPE , params ) , null , null ) ; mv . visitCode ( ) ; Label l0 = null ; if ( this . debug ) { l0 = new Label ( ) ; mv . visitLabel ( l0 ) ; } fieldConstructorStart ( mv , classDef , fieldDefs ) ; mv . visitInsn ( Opcodes . RETURN ) ; Label l1 = null ; if ( this . debug ) { l1 = new Label ( ) ; mv . visitLabel ( l1 ) ; mv . visitLocalVariable ( "this" , BuildUtils . getTypeDescriptor ( classDef . getClassName ( ) ) , null , l0 , l1 , 0 ) ; for ( FieldDefinition field : classDef . getFieldsDefinitions ( ) ) { Label l11 = new Label ( ) ; mv . visitLabel ( l11 ) ; mv . visitLocalVariable ( field . getName ( ) , BuildUtils . getTypeDescriptor ( field . getTypeName ( ) ) , null , l0 , l1 , 0 ) ; } } mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; }
Creates a constructor that takes and assigns values to all fields in the order they are declared .
7,756
protected void buildGetMethod ( ClassVisitor cw , ClassDefinition classDef , FieldDefinition fieldDef ) { MethodVisitor mv ; { mv = cw . visitMethod ( Opcodes . ACC_PUBLIC , fieldDef . getReadMethod ( ) , Type . getMethodDescriptor ( Type . getType ( BuildUtils . getTypeDescriptor ( fieldDef . getTypeName ( ) ) ) , new Type [ ] { } ) , null , null ) ; mv . visitCode ( ) ; Label l0 = null ; if ( this . debug ) { l0 = new Label ( ) ; mv . visitLabel ( l0 ) ; } mv . visitVarInsn ( Opcodes . ALOAD , 0 ) ; if ( ! fieldDef . hasOverride ( ) ) { mv . visitFieldInsn ( Opcodes . GETFIELD , BuildUtils . getInternalType ( classDef . getClassName ( ) ) , fieldDef . getName ( ) , BuildUtils . getTypeDescriptor ( fieldDef . getTypeName ( ) ) ) ; mv . visitInsn ( Type . getType ( BuildUtils . getTypeDescriptor ( fieldDef . getTypeName ( ) ) ) . getOpcode ( Opcodes . IRETURN ) ) ; } else { mv . visitMethodInsn ( INVOKESPECIAL , BuildUtils . getInternalType ( classDef . getSuperClass ( ) ) , BuildUtils . getterName ( fieldDef . getName ( ) , fieldDef . getOverriding ( ) ) , Type . getMethodDescriptor ( Type . getType ( BuildUtils . getTypeDescriptor ( fieldDef . getOverriding ( ) ) ) , new Type [ ] { } ) , false ) ; mv . visitTypeInsn ( CHECKCAST , BuildUtils . getInternalType ( fieldDef . getTypeName ( ) ) ) ; mv . visitInsn ( BuildUtils . returnType ( fieldDef . getTypeName ( ) ) ) ; } Label l1 = null ; if ( this . debug ) { l1 = new Label ( ) ; mv . visitLabel ( l1 ) ; mv . visitLocalVariable ( "this" , BuildUtils . getTypeDescriptor ( classDef . getClassName ( ) ) , null , l0 , l1 , 0 ) ; } mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; } }
Creates the get method for the given field definition
7,757
public void startElementBuilder ( final String tagName , final Attributes attrs ) { this . attrs = attrs ; this . characters = new StringBuilder ( ) ; final Element element = this . document . createElement ( tagName ) ; final int numAttrs = attrs . getLength ( ) ; for ( int i = 0 ; i < numAttrs ; ++ i ) { element . setAttribute ( attrs . getLocalName ( i ) , attrs . getValue ( i ) ) ; } if ( this . configurationStack . isEmpty ( ) ) { this . configurationStack . addLast ( element ) ; } else { ( ( Element ) this . configurationStack . getLast ( ) ) . appendChild ( element ) ; this . configurationStack . addLast ( element ) ; } }
Start a configuration node .
7,758
public Element endElementBuilder ( ) { final Element element = ( Element ) this . configurationStack . removeLast ( ) ; if ( this . characters != null ) { element . appendChild ( this . document . createTextNode ( this . characters . toString ( ) ) ) ; } this . characters = null ; return element ; }
End a configuration node .
7,759
private void initEntityResolver ( ) { final String entityResolveClazzName = System . getProperty ( ExtensibleXmlParser . ENTITY_RESOLVER_PROPERTY_NAME ) ; if ( entityResolveClazzName != null && entityResolveClazzName . length ( ) > 0 ) { try { final Class entityResolverClazz = classLoader . loadClass ( entityResolveClazzName ) ; this . entityResolver = ( EntityResolver ) entityResolverClazz . newInstance ( ) ; } catch ( final Exception ignoreIt ) { } } }
Initializes EntityResolver that is configured via system property ENTITY_RESOLVER_PROPERTY_NAME .
7,760
public static ProcessPackage getOrCreate ( ResourceTypePackageRegistry rtps ) { ProcessPackage rtp = ( ProcessPackage ) rtps . get ( ResourceType . BPMN2 ) ; if ( rtp == null ) { rtp = new ProcessPackage ( ) ; rtps . put ( ResourceType . BPMN2 , rtp ) ; rtps . put ( ResourceType . DRF , rtp ) ; rtps . put ( ResourceType . CMMN , rtp ) ; } return rtp ; }
Finds or creates and registers a package in the given registry instance
7,761
public PatternDescr getBasePattern ( ) { if ( this . patterns . size ( ) > 1 ) { return ( PatternDescr ) this . patterns . get ( 0 ) ; } else if ( this . patterns . size ( ) == 1 ) { PatternDescr original = ( PatternDescr ) this . patterns . get ( 0 ) ; PatternDescr base = ( PatternDescr ) original . clone ( ) ; base . getDescrs ( ) . clear ( ) ; base . setIdentifier ( BASE_IDENTIFIER ) ; base . setResource ( original . getResource ( ) ) ; return base ; } return null ; }
Returns the base pattern from the forall CE
7,762
public List < BaseDescr > getRemainingPatterns ( ) { if ( this . patterns . size ( ) > 1 ) { return this . patterns . subList ( 1 , this . patterns . size ( ) ) ; } else if ( this . patterns . size ( ) == 1 ) { PatternDescr original = ( PatternDescr ) this . patterns . get ( 0 ) ; PatternDescr remaining = ( PatternDescr ) original . clone ( ) ; remaining . addConstraint ( new ExprConstraintDescr ( "this == " + BASE_IDENTIFIER ) ) ; remaining . setResource ( original . getResource ( ) ) ; return Collections . singletonList ( ( BaseDescr ) remaining ) ; } return Collections . emptyList ( ) ; }
Returns the remaining patterns from the forall CE
7,763
public Map < String , Declaration > getInnerDeclarations ( ) { final Map inner = new HashMap ( this . basePattern . getOuterDeclarations ( ) ) ; for ( Pattern pattern : remainingPatterns ) { inner . putAll ( pattern . getOuterDeclarations ( ) ) ; } return inner ; }
Forall inner declarations are only provided by the base patterns since it negates the remaining patterns
7,764
public void addProcess ( Process process ) { ResourceTypePackageRegistry rtps = getResourceTypePackages ( ) ; ProcessPackage rtp = ProcessPackage . getOrCreate ( rtps ) ; rtp . add ( process ) ; }
Add a rule flow to this package .
7,765
public Map < String , Process > getRuleFlows ( ) { ProcessPackage rtp = ( ProcessPackage ) getResourceTypePackages ( ) . get ( ResourceType . BPMN2 ) ; return rtp == null ? Collections . emptyMap ( ) : rtp . getRuleFlows ( ) ; }
Get the rule flows for this package . The key is the ruleflow id . It will be Collections . EMPTY_MAP if none have been added .
7,766
public void removeRuleFlow ( String id ) { ProcessPackage rtp = ( ProcessPackage ) getResourceTypePackages ( ) . get ( ResourceType . BPMN2 ) ; if ( rtp == null || rtp . lookup ( id ) == null ) { throw new IllegalArgumentException ( "The rule flow with id [" + id + "] is not part of this package." ) ; } rtp . remove ( id ) ; }
Rule flows can be removed by ID .
7,767
public void addDSLMapping ( final DSLMapping mapping ) { for ( DSLMappingEntry entry : mapping . getEntries ( ) ) { if ( DSLMappingEntry . KEYWORD . equals ( entry . getSection ( ) ) ) { this . keywords . add ( entry ) ; } else if ( DSLMappingEntry . CONDITION . equals ( entry . getSection ( ) ) ) { this . condition . add ( entry ) ; } else if ( DSLMappingEntry . CONSEQUENCE . equals ( entry . getSection ( ) ) ) { this . consequence . add ( entry ) ; } else { this . condition . add ( entry ) ; this . consequence . add ( entry ) ; } } if ( mapping . getOption ( "result" ) ) showResult = true ; if ( mapping . getOption ( "steps" ) ) showSteps = true ; if ( mapping . getOption ( "keyword" ) ) showKeyword = true ; if ( mapping . getOption ( "when" ) ) showWhen = true ; if ( mapping . getOption ( "then" ) ) showThen = true ; if ( mapping . getOption ( "usage" ) ) showUsage = true ; }
Add the new mapping to this expander .
7,768
private StringBuffer expandConstructions ( final String drl ) { if ( showKeyword ) { for ( DSLMappingEntry entry : this . keywords ) { logger . info ( "keyword: " + entry . getMappingKey ( ) ) ; logger . info ( " " + entry . getKeyPattern ( ) ) ; } } if ( showWhen ) { for ( DSLMappingEntry entry : this . condition ) { logger . info ( "when: " + entry . getMappingKey ( ) ) ; logger . info ( " " + entry . getKeyPattern ( ) ) ; } } if ( showThen ) { for ( DSLMappingEntry entry : this . consequence ) { logger . info ( "then: " + entry . getMappingKey ( ) ) ; logger . info ( " " + entry . getKeyPattern ( ) ) ; } } final Matcher m = finder . matcher ( drl ) ; final StringBuffer buf = new StringBuffer ( ) ; int drlPos = 0 ; int linecount = 0 ; while ( m . find ( ) ) { final StringBuilder expanded = new StringBuilder ( ) ; int newPos = m . start ( ) ; linecount += countNewlines ( drl , drlPos , newPos ) ; drlPos = newPos ; String constr = m . group ( ) . trim ( ) ; if ( constr . startsWith ( "rule" ) ) { String headerFragment = m . group ( 1 ) ; expanded . append ( headerFragment ) ; String lhsFragment = m . group ( 2 ) ; expanded . append ( this . expandLHS ( lhsFragment , linecount + countNewlines ( drl , drlPos , m . start ( 2 ) ) + 1 ) ) ; String thenFragment = m . group ( 3 ) ; expanded . append ( thenFragment ) ; String rhsFragment = this . expandRHS ( m . group ( 4 ) , linecount + countNewlines ( drl , drlPos , m . start ( 4 ) ) + 1 ) ; expanded . append ( rhsFragment ) ; expanded . append ( m . group ( 5 ) ) ; } else if ( constr . startsWith ( "query" ) ) { String fragment = m . group ( 6 ) ; expanded . append ( fragment ) ; String lhsFragment = this . expandLHS ( m . group ( 7 ) , linecount + countNewlines ( drl , drlPos , m . start ( 7 ) ) + 1 ) ; expanded . append ( lhsFragment ) ; expanded . append ( m . group ( 8 ) ) ; } else { this . addError ( new ExpanderException ( "Unable to expand statement: " + constr , 0 ) ) ; } m . appendReplacement ( buf , Matcher . quoteReplacement ( expanded . toString ( ) ) ) ; } m . appendTail ( buf ) ; return buf ; }
Expand constructions like rules and queries
7,769
private String cleanupExpressions ( String drl ) { for ( final DSLMappingEntry entry : this . cleanup ) { drl = entry . getKeyPattern ( ) . matcher ( drl ) . replaceAll ( entry . getValuePattern ( ) ) ; } return drl ; }
Clean up constructions that exists only in the unexpanded code
7,770
private String expandKeywords ( String drl ) { substitutions = new ArrayList < Map < String , String > > ( ) ; drl = substitute ( drl , this . keywords , 0 , useKeyword , false ) ; substitutions = null ; return drl ; }
Expand all configured keywords
7,771
private String expandLHS ( final String lhs , int lineOffset ) { substitutions = new ArrayList < Map < String , String > > ( ) ; final StringBuilder buf = new StringBuilder ( ) ; final String [ ] lines = lhs . split ( ( lhs . indexOf ( "\r\n" ) >= 0 ? "\r\n" : "\n" ) , - 1 ) ; final String [ ] expanded = new String [ lines . length ] ; int lastExpanded = - 1 ; int lastPattern = - 1 ; for ( int i = 0 ; i < lines . length - 1 ; i ++ ) { final String trimmed = lines [ i ] . trim ( ) ; expanded [ ++ lastExpanded ] = lines [ i ] ; if ( trimmed . length ( ) == 0 || trimmed . startsWith ( "#" ) || trimmed . startsWith ( "//" ) ) { } else if ( trimmed . startsWith ( ">" ) ) { expanded [ lastExpanded ] = lines [ i ] . replaceFirst ( ">" , " " ) ; lastPattern = lastExpanded ; } else { expanded [ lastExpanded ] = substitute ( expanded [ lastExpanded ] , this . condition , i + lineOffset , useWhen , showSteps ) ; if ( lines [ i ] . equals ( expanded [ lastExpanded ] ) ) { this . addError ( new ExpanderException ( "Unable to expand: " + lines [ i ] . replaceAll ( "[\n\r]" , "" ) . trim ( ) , i + lineOffset ) ) ; } if ( trimmed . startsWith ( "-" ) && ( ! lines [ i ] . equals ( expanded [ lastExpanded ] ) ) ) { if ( lastPattern >= 0 ) { ConstraintInformation c = ConstraintInformation . findConstraintInformationInPattern ( expanded [ lastPattern ] ) ; if ( c . start > - 1 ) { expanded [ lastPattern ] = expanded [ lastPattern ] . substring ( 0 , c . start ) + c . constraints + ( ( c . constraints . trim ( ) . length ( ) == 0 ) ? "" : ", " ) + expanded [ lastExpanded ] . trim ( ) + expanded [ lastPattern ] . substring ( c . end ) ; } else { this . addError ( new ExpanderException ( "No pattern was found to add the constraint to: " + lines [ i ] . trim ( ) , i + lineOffset ) ) ; } } lastExpanded -- ; } else { lastPattern = lastExpanded ; } } } for ( int i = 0 ; i <= lastExpanded ; i ++ ) { buf . append ( expanded [ i ] ) ; buf . append ( nl ) ; } return buf . toString ( ) ; }
Expand LHS for a construction
7,772
private String loadDrlFile ( final Reader drl ) throws IOException { final StringBuilder buf = new StringBuilder ( ) ; final BufferedReader input = new BufferedReader ( drl ) ; String line ; while ( ( line = input . readLine ( ) ) != null ) { buf . append ( line ) ; buf . append ( nl ) ; } return buf . toString ( ) ; }
Reads the stream into a String
7,773
public void addItemToActivationGroup ( final AgendaItem item ) { if ( item . isRuleAgendaItem ( ) ) { throw new UnsupportedOperationException ( "defensive programming, making sure this isn't called, before removing" ) ; } String group = item . getRule ( ) . getActivationGroup ( ) ; if ( group != null && group . length ( ) > 0 ) { InternalActivationGroup actgroup = getActivationGroup ( group ) ; if ( actgroup . getTriggeredForRecency ( ) != 0 && actgroup . getTriggeredForRecency ( ) >= item . getPropagationContext ( ) . getFactHandle ( ) . getRecency ( ) ) { return ; } actgroup . addActivation ( item ) ; } }
If the item belongs to an activation group add it
7,774
public Token emit ( ) { Token t = new DroolsToken ( input , state . type , state . channel , state . tokenStartCharIndex , getCharIndex ( ) - 1 ) ; t . setLine ( state . tokenStartLine ) ; t . setText ( state . text ) ; t . setCharPositionInLine ( state . tokenStartCharPositionInLine ) ; emit ( t ) ; return t ; }
The standard method called to automatically emit a token at the outermost lexical rule . The token object should point into the char buffer start .. stop . If there is a text override in text use that to set the token s text . Override this method to emit custom Token objects .
7,775
private void createClassDeclaration ( ) { builder . append ( "package " ) . append ( PACKAGE_NAME ) . append ( ";" ) . append ( NEWLINE ) ; builder . append ( "public class " ) . append ( generatedClassSimpleName ) . append ( " extends " ) . append ( CompiledNetwork . class . getName ( ) ) . append ( "{ " ) . append ( NEWLINE ) ; builder . append ( "org.drools.core.spi.InternalReadAccessor readAccessor;\n" ) ; }
This method will output the package statement followed by the opening of the class declaration
7,776
private void createConstructor ( Collection < HashedAlphasDeclaration > hashedAlphaDeclarations ) { builder . append ( "public " ) . append ( generatedClassSimpleName ) . append ( "(org.drools.core.spi.InternalReadAccessor readAccessor) {" ) . append ( NEWLINE ) ; builder . append ( "this.readAccessor = readAccessor;\n" ) ; for ( HashedAlphasDeclaration declaration : hashedAlphaDeclarations ) { String mapVariableName = declaration . getVariableName ( ) ; for ( Object hashedValue : declaration . getHashedValues ( ) ) { Object value = hashedValue ; if ( value == null ) { String nodeId = declaration . getNodeId ( hashedValue ) ; builder . append ( mapVariableName ) . append ( ".put(null," ) . append ( nodeId ) . append ( ");" ) ; builder . append ( NEWLINE ) ; } else { if ( value . getClass ( ) . equals ( String . class ) ) { value = "\"" + value + "\"" ; } else if ( value instanceof BigDecimal ) { value = "new java.math.BigDecimal(\"" + value + "\")" ; } else if ( value instanceof BigInteger ) { value = "new java.math.BigInteger(\"" + value + "\")" ; } String nodeId = declaration . getNodeId ( hashedValue ) ; builder . append ( mapVariableName ) . append ( ".put(" ) . append ( value ) . append ( ", " ) . append ( nodeId ) . append ( ");" ) ; builder . append ( NEWLINE ) ; } } } builder . append ( "}" ) . append ( NEWLINE ) ; }
Creates the constructor for the generated class . If the hashedAlphaDeclarations is empty it will just output a empty default constructor ; if it is not the constructor will contain code to fill the hash alpha maps with the values and node ids .
7,777
public boolean accept ( final AuditLogEntry entry ) { if ( ! acceptedTypes . containsKey ( entry . getGenericType ( ) ) ) { return false ; } return acceptedTypes . get ( entry . getGenericType ( ) ) ; }
This is the filtering method . When an AuditLogEntry is added to an AuditLog the AuditLog calls this method to determine whether the AuditLogEntry should be added .
7,778
private final static int onBreak ( Frame frame ) { if ( verbose ) { logger . info ( "Continuing with " + ( onBreakReturn == Debugger . CONTINUE ? "continue" : "step-over" ) ) ; } return onBreakReturn ; }
This is catched by the remote debugger
7,779
public void addConstraint ( final FieldConstraint constraint ) { if ( constraintList == null ) { constraintList = new CompositeFieldConstraint ( ) ; } this . constraintList . addConstraint ( constraint ) ; }
This will add a top level constraint .
7,780
protected void mergeTypeDeclarations ( TypeDeclaration oldDeclaration , TypeDeclaration newDeclaration ) { if ( oldDeclaration == null ) { return ; } for ( FieldDefinition oldFactField : oldDeclaration . getTypeClassDef ( ) . getFieldsDefinitions ( ) ) { FieldDefinition newFactField = newDeclaration . getTypeClassDef ( ) . getField ( oldFactField . getName ( ) ) ; if ( newFactField == null ) { newDeclaration . getTypeClassDef ( ) . addField ( oldFactField ) ; } } newDeclaration . setTypeClass ( oldDeclaration . getTypeClass ( ) ) ; }
Merges all the missing FactFields from oldDefinition into newDeclaration .
7,781
private void populateGlobalsMap ( Map < String , String > globs ) throws ClassNotFoundException { this . globals = new HashMap < String , Class < ? > > ( ) ; for ( Map . Entry < String , String > entry : globs . entrySet ( ) ) { addGlobal ( entry . getKey ( ) , this . rootClassLoader . loadClass ( entry . getValue ( ) ) ) ; } }
globals class types must be re - wired after serialization
7,782
private void populateTypeDeclarationMaps ( ) throws ClassNotFoundException { for ( InternalKnowledgePackage pkg : this . pkgs . values ( ) ) { for ( TypeDeclaration type : pkg . getTypeDeclarations ( ) . values ( ) ) { type . setTypeClass ( this . rootClassLoader . loadClass ( type . getTypeClassName ( ) ) ) ; this . classTypeDeclaration . put ( type . getTypeClassName ( ) , type ) ; } } }
type classes must be re - wired after serialization
7,783
public void reload ( ) { this . classLoader = makeClassLoader ( ) ; try { for ( Entry < String , Wireable > entry : invokerLookups . entrySet ( ) ) { wire ( classLoader , entry . getKey ( ) , entry . getValue ( ) , true ) ; } } catch ( final ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } catch ( final InstantiationError e ) { throw new RuntimeException ( e ) ; } catch ( final IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( final InstantiationException e ) { throw new RuntimeException ( e ) ; } this . dirty = false ; }
This class drops the classLoader and reloads it . During this process it must re - wire all the invokeables .
7,784
public void fireUntilHalt ( final AgendaFilter agendaFilter ) { if ( isSequential ( ) ) { throw new IllegalStateException ( "fireUntilHalt() can not be called in sequential mode." ) ; } try { startOperation ( ) ; agenda . fireUntilHalt ( agendaFilter ) ; } finally { endOperation ( ) ; } }
Keeps firing activations until a halt is called . If in a given moment there is no activation to fire it will wait for an activation to be added to an active agenda group or rule flow group .
7,785
public void endOperation ( ) { if ( this . opCounter . decrementAndGet ( ) == 0 ) { this . lastIdleTimestamp . set ( this . timerService . getCurrentTime ( ) ) ; if ( this . endOperationListener != null ) { this . endOperationListener . endOperation ( this . getKnowledgeRuntime ( ) ) ; } } }
This method must be called after finishing any work in the engine like inserting a new fact or firing a new rule . It will reset the engine idle time counter .
7,786
public boolean isEffective ( Tuple tuple , RuleTerminalNode rtn , WorkingMemory workingMemory ) { if ( ! this . enabled . getValue ( tuple , rtn . getEnabledDeclarations ( ) , this , workingMemory ) ) { return false ; } if ( this . dateEffective == null && this . dateExpires == null ) { return true ; } else { Calendar now = Calendar . getInstance ( ) ; now . setTimeInMillis ( workingMemory . getSessionClock ( ) . getCurrentTime ( ) ) ; if ( this . dateEffective != null && this . dateExpires != null ) { return ( now . after ( this . dateEffective ) && now . before ( this . dateExpires ) ) ; } else if ( this . dateEffective != null ) { return ( now . after ( this . dateEffective ) ) ; } else { return ( now . before ( this . dateExpires ) ) ; } } }
This returns true is the rule is effective . If the rule is not effective it cannot activate .
7,787
public GroupElement [ ] getTransformedLhs ( LogicTransformer transformer , Map < String , Class < ? > > globals ) throws InvalidPatternException { return transformer . transform ( getExtendedLhs ( this , null ) , globals ) ; }
Uses the LogicTransformer to process the Rule patters - if no ORs are used this will return an array of a single AND element . If there are Ors it will return an And element for each possible logic branch . The processing uses as a clone of the Rule s patterns so they are not changed .
7,788
public static boolean isVariableNamePartValid ( String namePart , Scope scope ) { if ( DIGITS_PATTERN . matcher ( namePart ) . matches ( ) ) { return true ; } if ( REUSABLE_KEYWORDS . contains ( namePart ) ) { return scope . followUp ( namePart , true ) ; } return isVariableNameValid ( namePart ) ; }
Either namePart is a string of digits or it must be a valid name itself
7,789
public boolean matches ( Class < ? > clazz ) { if ( this . target . equals ( clazz . getName ( ) ) ) { return true ; } if ( this . target . endsWith ( ".*" ) ) { String prefix = this . target . substring ( 0 , this . target . indexOf ( ".*" ) ) ; if ( prefix . equals ( clazz . getPackage ( ) . getName ( ) ) ) { return true ; } } return false ; }
Returns true if this ImportDeclaration correctly matches to the given clazz
7,790
public static StatefulKnowledgeSessionImpl readSession ( StatefulKnowledgeSessionImpl session , MarshallerReaderContext context ) throws IOException , ClassNotFoundException { ProtobufMessages . KnowledgeSession _session = loadAndParseSession ( context ) ; InternalAgenda agenda = resetSession ( session , context , _session ) ; readSession ( _session , session , agenda , context ) ; return session ; }
Stream the data into an existing session
7,791
public static ReadSessionResult readSession ( MarshallerReaderContext context , int id ) throws IOException , ClassNotFoundException { return readSession ( context , id , EnvironmentFactory . newEnvironment ( ) , new SessionConfigurationImpl ( ) ) ; }
Create a new session into which to read the stream data
7,792
public void compileAll ( ) { if ( this . generatedClassList . isEmpty ( ) ) { this . errorHandlers . clear ( ) ; return ; } final String [ ] classes = new String [ this . generatedClassList . size ( ) ] ; this . generatedClassList . toArray ( classes ) ; File dumpDir = this . configuration . getPackageBuilderConfiguration ( ) . getDumpDir ( ) ; if ( dumpDir != null ) { dumpResources ( classes , dumpDir ) ; } final CompilationResult result = this . compiler . compile ( classes , this . src , this . packageStoreWrapper , rootClassLoader ) ; if ( result . getErrors ( ) . length > 0 ) { for ( int i = 0 ; i < result . getErrors ( ) . length ; i ++ ) { final CompilationProblem err = result . getErrors ( ) [ i ] ; final ErrorHandler handler = this . errorHandlers . get ( err . getFileName ( ) ) ; handler . addError ( err ) ; } final Collection errors = this . errorHandlers . values ( ) ; for ( Object error : errors ) { final ErrorHandler handler = ( ErrorHandler ) error ; if ( handler . isInError ( ) ) { this . results . add ( handler . getError ( ) ) ; } } } this . generatedClassList . clear ( ) ; this . errorHandlers . clear ( ) ; }
This actually triggers the compiling of all the resources . Errors are mapped back to the element that originally generated the semantic code .
7,793
public void addRule ( final RuleBuildContext context ) { final RuleImpl rule = context . getRule ( ) ; final RuleDescr ruleDescr = context . getRuleDescr ( ) ; RuleClassBuilder classBuilder = context . getDialect ( ) . getRuleClassBuilder ( ) ; String ruleClass = classBuilder . buildRule ( context ) ; if ( ruleClass == null ) { return ; } addClassCompileTask ( this . pkg . getName ( ) + "." + ruleDescr . getClassName ( ) , ruleDescr , ruleClass , this . src , new RuleErrorHandler ( ruleDescr , rule , "Rule Compilation error" ) ) ; JavaDialectRuntimeData data = ( JavaDialectRuntimeData ) this . pkg . getDialectRuntimeRegistry ( ) . getDialectData ( ID ) ; for ( Map . Entry < String , String > invokers : context . getInvokers ( ) . entrySet ( ) ) { final String className = invokers . getKey ( ) ; final Object invoker = context . getInvokerLookup ( className ) ; if ( invoker instanceof Wireable ) { data . putInvoker ( className , ( Wireable ) invoker ) ; } final String text = invokers . getValue ( ) ; final BaseDescr descr = context . getDescrLookup ( className ) ; addClassCompileTask ( className , descr , text , this . src , new RuleInvokerErrorHandler ( descr , rule , "Unable to generate rule invoker." ) ) ; } final String name = this . pkg . getName ( ) + "." + StringUtils . ucFirst ( ruleDescr . getClassName ( ) ) ; final LineMappings mapping = new LineMappings ( name ) ; mapping . setStartLine ( ruleDescr . getConsequenceLine ( ) ) ; mapping . setOffset ( ruleDescr . getConsequenceOffset ( ) ) ; this . pkg . getDialectRuntimeRegistry ( ) . getLineMappings ( ) . put ( name , mapping ) ; }
This will add the rule for compiling later on . It will not actually call the compiler
7,794
public RuleConditionElement build ( final RuleBuildContext context , final BaseDescr descr , final Pattern prefixPattern ) { boolean typesafe = context . isTypesafe ( ) ; final EvalDescr evalDescr = ( EvalDescr ) descr ; try { MVELDialect dialect = ( MVELDialect ) context . getDialect ( "mvel" ) ; Map < String , Declaration > decls = context . getDeclarationResolver ( ) . getDeclarations ( context . getRule ( ) ) ; AnalysisResult analysis = context . getDialect ( ) . analyzeExpression ( context , evalDescr , evalDescr . getContent ( ) , new BoundIdentifiers ( DeclarationScopeResolver . getDeclarationClasses ( decls ) , context ) ) ; final BoundIdentifiers usedIdentifiers = analysis . getBoundIdentifiers ( ) ; int i = usedIdentifiers . getDeclrClasses ( ) . keySet ( ) . size ( ) ; Declaration [ ] previousDeclarations = new Declaration [ i ] ; i = 0 ; for ( String id : usedIdentifiers . getDeclrClasses ( ) . keySet ( ) ) { previousDeclarations [ i ++ ] = decls . get ( id ) ; } Arrays . sort ( previousDeclarations , SortDeclarations . instance ) ; MVELCompilationUnit unit = dialect . getMVELCompilationUnit ( ( String ) evalDescr . getContent ( ) , analysis , previousDeclarations , null , null , context , "drools" , KnowledgeHelper . class , false , MVELCompilationUnit . Scope . EXPRESSION ) ; final EvalCondition eval = new EvalCondition ( previousDeclarations ) ; MVELEvalExpression expr = new MVELEvalExpression ( unit , dialect . getId ( ) ) ; eval . setEvalExpression ( KiePolicyHelper . isPolicyEnabled ( ) ? new SafeEvalExpression ( expr ) : expr ) ; MVELDialectRuntimeData data = ( MVELDialectRuntimeData ) context . getPkg ( ) . getDialectRuntimeRegistry ( ) . getDialectData ( "mvel" ) ; data . addCompileable ( eval , expr ) ; expr . compile ( data , context . getRule ( ) ) ; return eval ; } catch ( final Exception e ) { copyErrorLocation ( e , evalDescr ) ; context . addError ( new DescrBuildError ( context . getParentDescr ( ) , evalDescr , e , "Unable to build expression for 'eval':" + e . getMessage ( ) + " '" + evalDescr . getContent ( ) + "'" ) ) ; return null ; } finally { context . setTypesafe ( typesafe ) ; } }
Builds and returns an Eval Conditional Element
7,795
public static Object div ( Object left , BigDecimal right ) { return right == null || right . signum ( ) == 0 ? null : InfixOpNode . div ( left , right , null ) ; }
to ground to null if right = 0
7,796
public static Boolean ne ( Object left , Object right ) { return not ( EvalHelper . isEqual ( left , right , null ) ) ; }
FEEL spec Table 39
7,797
public static Operator addOperatorToRegistry ( final String operatorId , final boolean isNegated ) { Operator op = new Operator ( operatorId , isNegated ) ; CACHE . put ( getKey ( operatorId , isNegated ) , op ) ; return op ; }
Creates a new Operator instance for the given parameters adds it to the registry and return it
7,798
public static Operator determineOperator ( final String operatorId , final boolean isNegated ) { Operator op = CACHE . get ( getKey ( operatorId , isNegated ) ) ; return op ; }
Returns the operator instance for the given parameters
7,799
private void filterLogEvent ( final LogEvent logEvent ) { for ( ILogEventFilter filter : this . filters ) { if ( ! filter . acceptEvent ( logEvent ) ) { return ; } } logEventCreated ( logEvent ) ; }
This method is invoked every time a new log event is created . It filters out unwanted events .