diff --git a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java index 1f5ba248ffc..efb70b91435 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java @@ -36,6 +36,7 @@ import java.util.Set; import java.util.Stack; import java.util.UUID; +import java.util.concurrent.ExecutionException; import java.util.function.Supplier; import org.drools.compiler.compiler.AnnotationDeclarationError; @@ -1148,8 +1149,7 @@ private Map preProcessRules(PackageDescr packageDescr, } if (needsRemoval) { - try { - this.kBase.lock(); + kBase.enqueueModification( () -> { for( org.kie.api.definition.rule.Rule rule : pkg.getRules() ) { if (filterAcceptsRemoval( ResourceChange.Type.RULE, rule.getPackageName(), rule.getName() ) ) { this.kBase.removeRule(pkg, pkg.getRule(rule.getName())); @@ -1169,9 +1169,7 @@ private Map preProcessRules(PackageDescr packageDescr, if (!rulesToBeRemoved.isEmpty()) { kBase.removeRules( pkg, rulesToBeRemoved ); } - } finally { - this.kBase.unlock(); - } + } ); } } @@ -1580,13 +1578,10 @@ public PackageRegistry newPackage(final PackageDescr packageDescr) { // if there is a rulebase then add the package. if (this.kBase != null) { - // Must lock here, otherwise the assumption about addPackage/getPackage behavior below might be violated - this.kBase.lock(); try { - this.kBase.addPackage(pkg); - pkg = this.kBase.getPackage(packageDescr.getName()); - } finally { - this.kBase.unlock(); + pkg = (InternalKnowledgePackage) this.kBase.addPackage(pkg).get(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException( e ); } } else { // the RuleBase will also initialise the diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java index d43ae4f9265..2823d720750 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java @@ -260,13 +260,8 @@ private Results update(final InternalKieModule currentKM, final ReleaseId newRel kbasesToRemove.add( kbaseName ); } else { final InternalKnowledgeBase kBase = (InternalKnowledgeBase) kBaseEntry.getValue(); - kBase.enqueueModification( new Runnable() { - @Override - public void run() { - updateKBase( kBase, currentKM, newReleaseId, newKM, cs, modifiedClasses, modifyingUsedClass, - unchangedResources, results, newKieBaseModel, currentKieBaseModel); - } - } ); + kBase.enqueueModification( () -> updateKBase( kBase, currentKM, newReleaseId, newKM, cs, modifiedClasses, modifyingUsedClass, + unchangedResources, results, newKieBaseModel, currentKieBaseModel ) ); } } diff --git a/drools-compiler/src/test/java/org/drools/compiler/builder/impl/KnowledgeBuilderTest.java b/drools-compiler/src/test/java/org/drools/compiler/builder/impl/KnowledgeBuilderTest.java index 5d15d45a208..86def2df1c5 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/builder/impl/KnowledgeBuilderTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/builder/impl/KnowledgeBuilderTest.java @@ -182,7 +182,7 @@ public void testReload() throws Exception { builder.getErrors().getErrors() ); InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase(); - kBase.getGlobals().put( "map", Map.class ); + kBase.addGlobal( "map", Map.class ); final KieSession workingMemory = kBase.newKieSession(); final HashMap map = new HashMap(); diff --git a/drools-compiler/src/test/java/org/drools/compiler/command/KBuilderBatchExecutionTest.java b/drools-compiler/src/test/java/org/drools/compiler/command/KBuilderBatchExecutionTest.java deleted file mode 100644 index d345b598073..00000000000 --- a/drools-compiler/src/test/java/org/drools/compiler/command/KBuilderBatchExecutionTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -package org.drools.compiler.command; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.drools.compiler.CommonTestMethodBase; -import org.drools.compiler.integrationtests.DroolsTest; -import org.drools.core.command.builder.KnowledgeBuilderAddCommand; -import org.drools.core.command.builder.KnowledgeBuilderGetErrorsCommand; -import org.drools.core.command.builder.KnowledgeBuilderGetKnowledgePackagesCommand; -import org.drools.core.command.builder.KnowledgeBuilderHasErrorsCommand; -import org.drools.core.command.builder.NewKnowledgeBuilderCommand; -import org.drools.core.impl.InternalKnowledgeBase; -import org.drools.core.impl.KnowledgeBaseFactory; -import org.drools.compiler.integrationtests.DroolsTest.Bar; -import org.drools.compiler.integrationtests.DroolsTest.Foo; -import org.junit.After; -import org.junit.Test; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.internal.builder.KnowledgeBuilderError; -import org.kie.internal.builder.KnowledgeBuilderErrors; -import org.kie.api.KieBase; -import org.kie.api.command.Command; -import org.kie.api.definition.KiePackage; -import org.kie.internal.command.CommandFactory; -import org.kie.internal.io.ResourceFactory; -import org.kie.internal.runtime.StatefulKnowledgeSession; -import org.kie.api.io.Resource; -import org.kie.api.io.ResourceType; -import org.kie.api.runtime.ExecutionResults; -import org.kie.api.runtime.KieSession; - -public class KBuilderBatchExecutionTest extends CommonTestMethodBase { - - private static final String source = "org/drools/compiler/lang/misplaced_parenthesis.drl"; - - private KieSession ksession = null; - - @After - public void disposeKSession() throws Exception { - if( ksession != null ) { - ksession.dispose(); - ksession = null; - } - } - - @Test - public void testKBuilderAdd() throws Exception { - Resource res = ResourceFactory.newClassPathResource(source); - assertNotNull(res); - - KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - ksession = createKnowledgeSession(kbase); - - List> commands = new ArrayList>(); - commands.add(new NewKnowledgeBuilderCommand("kbuilder")); - commands.add(new KnowledgeBuilderAddCommand(res, ResourceType.DRL, null)); - Command cmds = CommandFactory.newBatchExecution( commands ); - - ExecutionResults result = (ExecutionResults) ksession.execute( cmds ); - - assertNotNull(result); - Object kbuilder = result.getValue("kbuilder"); - assertNotNull(kbuilder); - assertTrue(kbuilder instanceof KnowledgeBuilder); - assertTrue(((KnowledgeBuilder) kbuilder).hasErrors()); - } - - @Test - public void testHasErrors() throws Exception { - Resource res = ResourceFactory.newClassPathResource(source); - assertNotNull(res); - - KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - ksession = createKnowledgeSession(kbase); - - List> commands = new ArrayList>(); - commands.add(new NewKnowledgeBuilderCommand()); - commands.add(new KnowledgeBuilderAddCommand(res, ResourceType.DRL, null)); - commands.add(new KnowledgeBuilderHasErrorsCommand("hasErrors")); - Command cmds = CommandFactory.newBatchExecution( commands ); - - ExecutionResults result = (ExecutionResults) ksession.execute( cmds ); - - assertNotNull(result); - Object hasErrors = result.getValue("hasErrors"); - assertNotNull(hasErrors); - assertEquals(Boolean.TRUE, hasErrors); - } - - @Test - public void testBatchGetErrors() throws Exception { - Resource res = ResourceFactory.newClassPathResource(source); - assertNotNull(res); - - KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - ksession = createKnowledgeSession(kbase); - - List> commands = new ArrayList>(); - commands.add(new NewKnowledgeBuilderCommand()); - commands.add(new KnowledgeBuilderAddCommand(res, ResourceType.DRL, null)); - commands.add(new KnowledgeBuilderGetErrorsCommand("errors")); - Command cmds = CommandFactory.newBatchExecution( commands ); - - ExecutionResults result = (ExecutionResults) ksession.execute( cmds ); - - assertNotNull(result); - Object errors = result.getValue("errors"); - assertNotNull(errors); - assertTrue(errors instanceof KnowledgeBuilderErrors); - KnowledgeBuilderErrors kbErrors = (KnowledgeBuilderErrors) errors; - - assertEquals( 2, kbErrors.size()); - KnowledgeBuilderError kbError = kbErrors.iterator().next(); - assertTrue( kbError.getMessage().startsWith("[ERR 102]")); - } - - @Test - @SuppressWarnings("unchecked") - public void testGetKnowledgePackages() { - int NUM_FACTS = 5; - int startCounter = counter; - - String ruleString - = "package org.drools.compiler.integrationtests;\n" - + "import " + KBuilderBatchExecutionTest.class.getCanonicalName() + ";\n" - + "import " + DroolsTest.class.getName() + ".Foo;\n" - + "import " + DroolsTest.class.getName() + ".Bar;\n" - + "rule test\n" - + "when\n" - + " Foo($p : id, id < " + Integer.toString( NUM_FACTS ) + ")\n" - + " Bar(id == $p)\n" - + "then\n" - + " " + KBuilderBatchExecutionTest.class.getSimpleName() + ".incCounter();\n" - + "end\n"; - - InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - ksession = createKnowledgeSession(kbase); - - List> commands = new ArrayList>(); - commands.add(new NewKnowledgeBuilderCommand()); - commands.add(new KnowledgeBuilderAddCommand( ResourceFactory.newByteArrayResource(ruleString.getBytes()), ResourceType.DRL, null)); - commands.add(new KnowledgeBuilderGetKnowledgePackagesCommand("pkgs")); - Command cmds = CommandFactory.newBatchExecution( commands ); - - ExecutionResults result = (ExecutionResults) ksession.execute( cmds ); - assertNotNull(result); - Object pkgsObject = result.getValue("pkgs"); - assertTrue(pkgsObject != null && pkgsObject instanceof Collection); - kbase.addPackages( ((Collection) pkgsObject) ); - - ksession.dispose(); - ksession = createKnowledgeSession(kbase); - for ( int i = 0; i < NUM_FACTS; i++ ) { - ksession.insert( new Foo( i ) ); - ksession.insert( new Bar( i ) ); - } - ksession.fireAllRules(); - - assertEquals(startCounter + NUM_FACTS, counter); - } - - private static int counter = 0; - public static void incCounter() { - ++counter; - } - -} diff --git a/drools-core/src/main/java/org/drools/core/command/KnowledgeBaseAddKnowledgePackagesCommand.java b/drools-core/src/main/java/org/drools/core/command/KnowledgeBaseAddKnowledgePackagesCommand.java deleted file mode 100644 index ada75b9172a..00000000000 --- a/drools-core/src/main/java/org/drools/core/command/KnowledgeBaseAddKnowledgePackagesCommand.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2010 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.drools.core.command; - -import org.drools.core.command.impl.ExecutableCommand; -import org.drools.core.command.impl.RegistryContext; -import org.drools.core.impl.InternalKnowledgeBase; -import org.kie.api.KieBase; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.api.runtime.Context; - -public class KnowledgeBaseAddKnowledgePackagesCommand - implements - ExecutableCommand { - - public KnowledgeBaseAddKnowledgePackagesCommand() { - } - - public Void execute(Context context) { - KnowledgeBuilder kbuilder = ((RegistryContext) context).lookup(KnowledgeBuilder.class); - if (kbuilder.hasErrors()) { - throw new IllegalStateException("There are rule compilation errors:\n" + kbuilder.getErrors().toString()); - } - InternalKnowledgeBase kbase = (InternalKnowledgeBase) ((RegistryContext) context).lookup(KieBase.class); - kbase.addPackages( kbuilder.getKnowledgePackages() ); - return null; - } - -} diff --git a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderAddCommand.java b/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderAddCommand.java deleted file mode 100644 index 505003cd539..00000000000 --- a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderAddCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2010 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.drools.core.command.builder; - -import org.drools.core.command.impl.ExecutableCommand; -import org.drools.core.command.impl.RegistryContext; -import org.kie.api.io.Resource; -import org.kie.api.io.ResourceConfiguration; -import org.kie.api.io.ResourceType; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.api.runtime.Context; - -public class KnowledgeBuilderAddCommand - implements - ExecutableCommand { - - private Resource resource; - private ResourceType resourceType; - private ResourceConfiguration resourceConfiguration; - - public KnowledgeBuilderAddCommand(Resource resource, - ResourceType resourceType, - ResourceConfiguration resourceConfiguration) { - this.resource = resource; - this.resourceType = resourceType; - this.resourceConfiguration = resourceConfiguration; - } - - - public Void execute(Context context) { - KnowledgeBuilder kbuilder = ((RegistryContext) context).lookup(KnowledgeBuilder.class); - if ( resourceConfiguration == null ) { - kbuilder.add( resource, - resourceType ); - } else { - kbuilder.add( resource, - resourceType, - resourceConfiguration ); - } - return null; - } - -} diff --git a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderGetErrorsCommand.java b/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderGetErrorsCommand.java deleted file mode 100644 index cc1b081c0cc..00000000000 --- a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderGetErrorsCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2010 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.drools.core.command.builder; - -import org.drools.core.command.impl.ExecutableCommand; -import org.drools.core.command.impl.RegistryContext; -import org.drools.core.runtime.impl.ExecutionResultImpl; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.internal.builder.KnowledgeBuilderErrors; -import org.kie.api.runtime.Context; - -public class KnowledgeBuilderGetErrorsCommand - implements - ExecutableCommand { - - private String outIdentifier; - - public KnowledgeBuilderGetErrorsCommand() { - } - - public KnowledgeBuilderGetErrorsCommand(String outIdentifier) { - this.outIdentifier = outIdentifier; - } - - public KnowledgeBuilderErrors execute(Context context) { - KnowledgeBuilder kbuilder = ((RegistryContext) context).lookup( KnowledgeBuilder.class ); - KnowledgeBuilderErrors errors = kbuilder.getErrors(); - if ( this.outIdentifier != null ) { - ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, errors ); - } - return errors; - } - -} diff --git a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderGetKnowledgePackagesCommand.java b/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderGetKnowledgePackagesCommand.java deleted file mode 100644 index 66e3f876a6c..00000000000 --- a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderGetKnowledgePackagesCommand.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2010 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.drools.core.command.builder; - -import org.drools.core.command.impl.ExecutableCommand; -import org.drools.core.command.impl.RegistryContext; -import org.drools.core.runtime.impl.ExecutionResultImpl; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.api.definition.KiePackage; -import org.kie.api.runtime.Context; - -import java.util.Collection; - -public class KnowledgeBuilderGetKnowledgePackagesCommand - implements - ExecutableCommand> { - - private String outIdentifier; - - public KnowledgeBuilderGetKnowledgePackagesCommand() { - } - - public KnowledgeBuilderGetKnowledgePackagesCommand(String outIdentifier) { - this.outIdentifier = outIdentifier; - } - - public Collection execute(Context context) { - KnowledgeBuilder kbuilder = ((RegistryContext) context).lookup(KnowledgeBuilder.class); - - Collection knowledgePackages = kbuilder.getKnowledgePackages(); - if ( this.outIdentifier != null ) { - ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, knowledgePackages ); - } - - return knowledgePackages; - } - -} diff --git a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderHasErrorsCommand.java b/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderHasErrorsCommand.java deleted file mode 100644 index 358781f5eb1..00000000000 --- a/drools-core/src/main/java/org/drools/core/command/builder/KnowledgeBuilderHasErrorsCommand.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2010 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.drools.core.command.builder; - -import org.drools.core.command.impl.ExecutableCommand; -import org.drools.core.command.impl.RegistryContext; -import org.drools.core.runtime.impl.ExecutionResultImpl; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.api.runtime.Context; - -public class KnowledgeBuilderHasErrorsCommand - implements - ExecutableCommand { - - private String outIdentifier; - - public KnowledgeBuilderHasErrorsCommand() { - } - - public KnowledgeBuilderHasErrorsCommand(String outIdentifier) { - this.outIdentifier = outIdentifier; - } - - public Boolean execute(Context context) { - KnowledgeBuilder kbuilder = ((RegistryContext) context).lookup(KnowledgeBuilder.class); - boolean errors = kbuilder.hasErrors(); - if ( this.outIdentifier != null ) { - ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, errors ); - } - return errors; - } - -} diff --git a/drools-core/src/main/java/org/drools/core/command/builder/NewKnowledgeBuilderCommand.java b/drools-core/src/main/java/org/drools/core/command/builder/NewKnowledgeBuilderCommand.java deleted file mode 100644 index 8b5684d89d6..00000000000 --- a/drools-core/src/main/java/org/drools/core/command/builder/NewKnowledgeBuilderCommand.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2010 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.drools.core.command.builder; - -import org.drools.core.command.impl.ExecutableCommand; -import org.drools.core.command.impl.RegistryContext; -import org.drools.core.runtime.impl.ExecutionResultImpl; -import org.drools.core.util.StringUtils; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.internal.builder.KnowledgeBuilderConfiguration; -import org.kie.internal.builder.KnowledgeBuilderFactory; -import org.kie.api.KieBase; -import org.kie.api.runtime.Context; - -public class NewKnowledgeBuilderCommand - implements - ExecutableCommand { - - private KnowledgeBuilderConfiguration kbuilderConf; - - private KieBase attachedKnowledgeBase; - - private String kbaseId; - - private String outIdentifier; - - public NewKnowledgeBuilderCommand() { - } - - public NewKnowledgeBuilderCommand(String outIdentifier) { - this.outIdentifier = outIdentifier; - } - - public NewKnowledgeBuilderCommand(KnowledgeBuilderConfiguration kbuilderConf) { - this.kbuilderConf = kbuilderConf; - } - - public NewKnowledgeBuilderCommand(KnowledgeBuilderConfiguration kbuilderConf, String kbaseId) { - this.kbuilderConf = kbuilderConf; - setAttachedKnowledgeBase( kbaseId ); - } - - public NewKnowledgeBuilderCommand(KnowledgeBuilderConfiguration kbuilderConf, String kbaseId, String outIdentifier) { - this.kbuilderConf = kbuilderConf; - setAttachedKnowledgeBase( kbaseId ); - this.outIdentifier = outIdentifier; - } - - public KieBase getAttachedKnowledgeBase() { - return attachedKnowledgeBase; - } - - public void setAttachedKnowledgeBase(KieBase attachedKnowledgeBase) { - this.attachedKnowledgeBase = attachedKnowledgeBase; - } - - public void setAttachedKnowledgeBase(String kbaseId) { - this.kbaseId = kbaseId; - } - - - - - public KnowledgeBuilder execute(Context context) { - KnowledgeBuilder kbuilder = null; - - if ( !StringUtils.isEmpty( kbaseId )) { - attachedKnowledgeBase = ( KieBase ) context.get( kbaseId ); - } - - if ( this.kbuilderConf == null ) { - kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(this.attachedKnowledgeBase); - } else { - kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( this.attachedKnowledgeBase, - this.kbuilderConf ); - } - - if ( context instanceof RegistryContext ) { - ((RegistryContext) context).register( KnowledgeBuilder.class, kbuilder ); - } - - if ( this.outIdentifier != null ) { - ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, kbuilder ); - } - - return kbuilder; - } - -} diff --git a/drools-core/src/main/java/org/drools/core/impl/InternalKnowledgeBase.java b/drools-core/src/main/java/org/drools/core/impl/InternalKnowledgeBase.java index 0ed4cb4588a..607a962b911 100644 --- a/drools-core/src/main/java/org/drools/core/impl/InternalKnowledgeBase.java +++ b/drools-core/src/main/java/org/drools/core/impl/InternalKnowledgeBase.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.Future; import org.drools.core.RuleBaseConfiguration; import org.drools.core.SessionConfiguration; @@ -60,9 +61,6 @@ public interface InternalKnowledgeBase extends KieBase { void readLock(); void readUnlock(); - void lock(); - void unlock(); - void enqueueModification(Runnable modification); boolean flushModifications(); @@ -113,8 +111,8 @@ void retractObject(FactHandle handle, Class registerAndLoadTypeDefinition( String className, byte[] def ) throws ClassNotFoundException; InternalKnowledgePackage getPackage(String name); - void addPackage(KiePackage pkg); - void addPackages( final Collection newPkgs ); + Future addPackage( KiePackage pkg ); + void addPackages( Collection newPkgs ); Map getPackagesMap(); ClassFieldAccessorCache getClassFieldAccessorCache(); diff --git a/drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseImpl.java b/drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseImpl.java index 71d25cb7f4d..2684972cc7e 100644 --- a/drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseImpl.java +++ b/drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseImpl.java @@ -21,10 +21,8 @@ import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; -import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -33,8 +31,10 @@ import java.util.Map; import java.util.Queue; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -98,22 +98,16 @@ import org.kie.api.definition.type.Expires.Policy; import org.kie.api.definition.type.FactType; import org.kie.api.definition.type.Role; -import org.kie.api.event.kiebase.BeforeRuleRemovedEvent; import org.kie.api.event.kiebase.KieBaseEventListener; import org.kie.api.io.Resource; import org.kie.api.io.ResourceType; -import org.kie.api.marshalling.Marshaller; -import org.kie.api.marshalling.ObjectMarshallingStrategy; import org.kie.api.runtime.Environment; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.KieSessionConfiguration; import org.kie.api.runtime.StatelessKieSession; import org.kie.api.runtime.rule.FactHandle; -import org.kie.internal.builder.InternalKieBuilder; import org.kie.internal.io.ResourceTypePackage; -import org.kie.internal.marshalling.MarshallerFactory; import org.kie.internal.runtime.StatefulKnowledgeSession; -import org.kie.internal.runtime.StatelessKnowledgeSession; import org.kie.internal.utils.ServiceRegistryImpl; import org.kie.internal.weaver.KieWeaverService; import org.kie.internal.weaver.KieWeavers; @@ -279,40 +273,11 @@ public Collection getKieBaseEventListeners() { return Collections.unmodifiableCollection( kieBaseListeners ); } - public StatefulKnowledgeSession newStatefulKnowledgeSession() { - return newStatefulKnowledgeSession(null, EnvironmentFactory.newEnvironment()); - } - - public StatefulKnowledgeSession newStatefulKnowledgeSession(KieSessionConfiguration conf, Environment environment) { - // NOTE if you update here, you'll also need to update the JPAService - if ( conf == null ) { - conf = getSessionConfiguration(); - } - - if ( environment == null ) { - environment = EnvironmentFactory.newEnvironment(); - } - - return newStatefulSession((SessionConfiguration) conf, environment); - } - public SessionConfiguration getSessionConfiguration() { return sessionConfiguration; } - public Collection getStatefulKnowledgeSessions() { - return statefulSessions; - } - - public StatelessKnowledgeSession newStatelessKnowledgeSession() { - return new StatelessKnowledgeSessionImpl( this, null ); - } - - public StatelessKnowledgeSession newStatelessKnowledgeSession(KieSessionConfiguration conf) { - return new StatelessKnowledgeSessionImpl( this, conf ); - } - - public void removeKnowledgePackage(String packageName) { + public void removeKiePackage(String packageName) { lock(); try { final InternalKnowledgePackage pkg = this.pkgs.get( packageName ); @@ -323,7 +288,7 @@ public void removeKnowledgePackage(String packageName) { this.eventSupport.fireBeforePackageRemoved( pkg ); for (Rule rule : pkg.getRules()) { - removeRule( pkg, (RuleImpl)rule ); + internalRemoveRule( pkg, (RuleImpl)rule ); } // getting the list of referenced globals @@ -341,7 +306,7 @@ public void removeKnowledgePackage(String packageName) { } //and now the rule flows for ( String processName : new ArrayList(pkg.getRuleFlows().keySet()) ) { - removeProcess( processName ); + internalRemoveProcess( processName ); } // removing the package itself from the list this.pkgs.remove( pkg.getName() ); @@ -368,13 +333,39 @@ public Query getQuery(String packageName, return getPackage(packageName).getRule( queryName ); } - public KieSession newKieSession(KieSessionConfiguration conf, - Environment environment) { - return newStatefulKnowledgeSession( conf, environment ); + public KieSession newKieSession() { + return newKieSession(null, EnvironmentFactory.newEnvironment()); } - public KieSession newKieSession() { - return newStatefulKnowledgeSession(); + public KieSession newKieSession(KieSessionConfiguration conf, Environment environment) { + // NOTE if you update here, you'll also need to update the JPAService + if ( conf == null ) { + conf = getSessionConfiguration(); + } + + SessionConfiguration sessionConfig = (SessionConfiguration) conf; + + if ( environment == null ) { + environment = EnvironmentFactory.newEnvironment(); + } + + if ( this.getConfiguration().isSequential() ) { + throw new RuntimeException( "Cannot have a stateful rule session, with sequential configuration set to true" ); + } + + readLock(); + try { + WorkingMemoryFactory wmFactory = kieComponentFactory.getWorkingMemoryFactory(); + StatefulKnowledgeSessionImpl session = ( StatefulKnowledgeSessionImpl ) wmFactory.createWorkingMemory( nextWorkingMemoryCounter(), this, + sessionConfig, environment ); + if ( sessionConfig.isKeepReference() ) { + addStatefulSession(session); + } + + return session; + } finally { + readUnlock(); + } } public Collection getKieSessions() { @@ -386,11 +377,11 @@ public Collection getKieSessions() { } public StatelessKieSession newStatelessKieSession(KieSessionConfiguration conf) { - return newStatelessKnowledgeSession( conf ); + return new StatelessKnowledgeSessionImpl( this, conf ); } public StatelessKieSession newStatelessKieSession() { - return newStatelessKnowledgeSession(); + return new StatelessKnowledgeSessionImpl( this, null ); } public Collection getKiePackages() { @@ -404,11 +395,6 @@ public KiePackage getKiePackage(String packageName) { return getPackage(packageName); } - public void removeKiePackage(String packageName) { - removeKnowledgePackage(packageName); - } - - // ------------------------------------------------------------ // Instance methods // ------------------------------------------------------------ @@ -468,12 +454,8 @@ public void readExternal(final ObjectInput in) throws IOException, try { cls = droolsStream.getParentClassLoader().loadClass(droolsStream.readUTF()); this.factHandleFactory = (FactHandleFactory) cls.newInstance(); - } catch (InstantiationException e) { - DroolsObjectInputStream.newInvalidClassException(cls, - e); - } catch (IllegalAccessException e) { - DroolsObjectInputStream.newInvalidClassException(cls, - e); + } catch (InstantiationException | IllegalAccessException e) { + DroolsObjectInputStream.newInvalidClassException(cls, e); } for (InternalKnowledgePackage pkg : this.pkgs.values()) { @@ -635,15 +617,6 @@ public String getId() { return this.id; } - public RuleBaseConfiguration getConfig() { - return config; - } - - public StatefulKnowledgeSessionImpl newStatefulSession() { - return newStatefulSession(getSessionConfiguration(), - EnvironmentFactory.newEnvironment()); - } - public void disposeStatefulSession(StatefulKnowledgeSessionImpl statefulSession) { synchronized (statefulSessions) { if (sessionsCache != null) { @@ -657,10 +630,6 @@ public StatefulKnowledgeSessionImpl getCachedSession(SessionConfiguration config return sessionsCache != null ? sessionsCache.getCachedSession(config) : null; } - public FactHandleFactory getFactHandleFactory() { - return this.factHandleFactory; - } - public FactHandleFactory newFactHandleFactory() { return this.factHandleFactory.newInstance(); } @@ -701,7 +670,7 @@ public Map> getGlobals() { return this.globals; } - public void lock() { + private void lock() { // The lock is reentrant, so we need additional magic here to skip // notifications for locked if this thread already has locked it. boolean firstLock = !this.lock.isWriteLockedByCurrentThread(); @@ -715,7 +684,7 @@ public void lock() { } } - public void unlock() { + private void unlock() { boolean lastUnlock = this.lock.getWriteHoldCount() == 1; if (lastUnlock) { this.eventSupport.fireBeforeRuleBaseUnlocked(); @@ -743,23 +712,24 @@ public void readUnlock() { * @param newPkgs The package to add. */ @Override - public void addPackages( final Collection newPkgs ) { + public void addPackages( Collection newPkgs ) { final List clonedPkgs = new ArrayList(); for (KiePackage newPkg : newPkgs) { clonedPkgs.add(((InternalKnowledgePackage)newPkg).deepCloneIfAlreadyInUse(rootClassLoader)); } - enqueueModification(new Runnable() { - @Override - public void run() { - internalAddPackages(clonedPkgs); - } - }); + enqueueModification( () -> internalAddPackages( clonedPkgs ) ); } @Override - public void addPackage(final KiePackage newPkg) { - addPackages( Collections.singleton(newPkg) ); + public Future addPackage( final KiePackage newPkg ) { + InternalKnowledgePackage clonedPkg = ((InternalKnowledgePackage)newPkg).deepCloneIfAlreadyInUse(rootClassLoader); + CompletableFuture result = new CompletableFuture<>(); + enqueueModification( () -> { + internalAddPackages( Collections.singletonList(clonedPkg) ); + result.complete( getPackage(newPkg.getName()) ); + } ); + return result; } public void enqueueModification(Runnable modification) { @@ -890,9 +860,7 @@ private void internalAddPackages(List clonedPkgs) { for ( InternalKnowledgePackage newPkg : clonedPkgs ) { // we have to do this before the merging, as it does some classloader resolving if ( newPkg.getTypeDeclarations() != null ) { - for ( TypeDeclaration newDecl : newPkg.getTypeDeclarations().values() ) { - allTypeDeclarations.add( newDecl ); - } + allTypeDeclarations.addAll( newPkg.getTypeDeclarations().values() ); } } Collections.sort(allTypeDeclarations); @@ -957,27 +925,26 @@ private void internalAddPackages(List clonedPkgs) { // add the window declarations to the kbase for( WindowDeclaration window : newPkg.getWindowDeclarations().values() ) { - addWindowDeclaration( window ); + this.reteooBuilder.addNamedWindow(window); } // add entry points to the kbase for (String id : newPkg.getEntryPointIds()) { - addEntryPoint( id ); + this.reteooBuilder.addEntryPoint(id); } // add the rules to the RuleBase for ( Rule r : newPkg.getRules() ) { RuleImpl rule = (RuleImpl)r; checkMultithreadedEvaluation( rule ); - addRule( newPkg, rule ); + internalAddRule( newPkg, rule ); } // add the flows to the RuleBase if ( newPkg.getRuleFlows() != null ) { final Map flows = newPkg.getRuleFlows(); for ( Process process : flows.values() ) { - // XXX: we could take the lock inside addProcess() out, but OTOH: this is what the VM is supposed to do ... - addProcess( process ); + internalAddProcess( process ); } } @@ -1466,107 +1433,6 @@ public void retractObject(final FactHandle handle, workingMemory); } - public StatefulKnowledgeSessionImpl newStatefulSession(boolean keepReference) { - SessionConfiguration config = getSessionConfiguration(); - config.setKeepReference( keepReference ); - - return newStatefulSession( config, - EnvironmentFactory.newEnvironment() ); - } - - public StatefulKnowledgeSessionImpl newStatefulSession(java.io.InputStream stream) { - return newStatefulSession( stream, - true ); - } - - public StatefulKnowledgeSessionImpl newStatefulSession(java.io.InputStream stream, - boolean keepReference) { - return newStatefulSession( stream, - keepReference, - getSessionConfiguration() ); - } - - public StatefulKnowledgeSessionImpl newStatefulSession(java.io.InputStream stream, - boolean keepReference, - SessionConfiguration conf) { - StatefulKnowledgeSessionImpl session; - try { - readLock(); - try { - // first unwrap the byte[] - ObjectInputStream ois = new ObjectInputStream( stream ); - - // standard serialisation would have written the statateful session instance info to the stream first - // so we read it, but we don't need it, so just ignore. - StatefulKnowledgeSessionImpl rsession = (StatefulKnowledgeSessionImpl) ois.readObject(); - - // now unmarshall that byte[] - ByteArrayInputStream bais = new ByteArrayInputStream( rsession.bytes ); - Marshaller marshaller = MarshallerFactory.newMarshaller(this, new ObjectMarshallingStrategy[]{MarshallerFactory.newSerializeMarshallingStrategy()}); - - Environment environment = EnvironmentFactory.newEnvironment(); - KieSession ksession = marshaller.unmarshall( bais, - conf, - environment ); - session = (StatefulKnowledgeSessionImpl) ksession; - - if ( keepReference ) { - addStatefulSession(session); - } - - bais.close(); - } finally { - readUnlock(); - } - - } catch ( Exception e ) { - throw new RuntimeException( "Unable to unmarshall session", - e ); - } finally { - try { - stream.close(); - } catch ( IOException e ) { - throw new RuntimeException( "Unable to close stream", e ); - } - } - return session; - } - - public StatefulKnowledgeSessionImpl newStatefulSession(SessionConfiguration sessionConfig, - Environment environment) { - if ( sessionConfig == null ) { - sessionConfig = getSessionConfiguration(); - } - if ( environment == null ) { - environment = EnvironmentFactory.newEnvironment(); - } - return newStatefulSession( nextWorkingMemoryCounter(), - sessionConfig, - environment ); - } - - StatefulKnowledgeSessionImpl newStatefulSession(int id, - SessionConfiguration sessionConfig, - Environment environment) { - if ( this.getConfiguration().isSequential() ) { - throw new RuntimeException( "Cannot have a stateful rule session, with sequential configuration set to true" ); - } - - readLock(); - try { - WorkingMemoryFactory wmFactory = kieComponentFactory.getWorkingMemoryFactory(); - StatefulKnowledgeSessionImpl session = ( StatefulKnowledgeSessionImpl ) wmFactory.createWorkingMemory( id, this, - sessionConfig, environment ); - if ( sessionConfig.isKeepReference() ) { - addStatefulSession(session); - } - - return session; - } finally { - readUnlock(); - } - } - public int getNodeCount() { // may start in 0 return this.reteooBuilder.getIdGenerator().getLastId() + 1; @@ -1684,32 +1550,16 @@ public void addRule( final InternalKnowledgePackage pkg, final RuleImpl rule ) throws InvalidPatternException { lock(); try { - this.eventSupport.fireBeforeRuleAdded( pkg, - rule ); - // if ( !rule.isValid() ) { - // throw new IllegalArgumentException( "The rule called " + rule.getName() + " is not valid. Check for compile errors reported." ); - // } - addRule( rule ); - this.eventSupport.fireAfterRuleAdded(pkg, - rule); + internalAddRule( pkg, rule ); } finally { unlock(); } } - protected void addRule(final RuleImpl rule) throws InvalidPatternException { - // This adds the rule. ReteBuilder has a reference to the WorkingMemories and will propagate any existing facts. + private void internalAddRule( InternalKnowledgePackage pkg, RuleImpl rule ) { + this.eventSupport.fireBeforeRuleAdded( pkg, rule ); this.reteooBuilder.addRule(rule); - } - - protected void addEntryPoint(final String id) throws InvalidPatternException { - // This adds the entry point. ReteBuilder has a reference to the WorkingMemories and will propagate any existing facts. - this.reteooBuilder.addEntryPoint(id); - } - - private void addWindowDeclaration(final WindowDeclaration window) throws InvalidPatternException { - // This adds the named window. ReteBuilder has a reference to the WorkingMemories and will propagate any existing facts. - this.reteooBuilder.addNamedWindow(window); + this.eventSupport.fireAfterRuleAdded(pkg, rule); } public void removeQuery( final String packageName, @@ -1720,29 +1570,26 @@ public void removeQuery( final String packageName, public void removeRule( final String packageName, final String ruleName ) { - enqueueModification(new Runnable() { - @Override - public void run() { - final InternalKnowledgePackage pkg = pkgs.get( packageName ); - if (pkg == null) { - throw new IllegalArgumentException( "Package name '" + packageName + - "' does not exist for this Rule Base." ); - } + enqueueModification( () -> { + final InternalKnowledgePackage pkg = pkgs.get( packageName ); + if (pkg == null) { + throw new IllegalArgumentException( "Package name '" + packageName + + "' does not exist for this Rule Base." ); + } - RuleImpl rule = pkg.getRule( ruleName ); - if (rule == null) { - throw new IllegalArgumentException( "Rule name '" + ruleName + - "' does not exist in the Package '" + - packageName + - "'." ); - } + RuleImpl rule = pkg.getRule( ruleName ); + if (rule == null) { + throw new IllegalArgumentException( "Rule name '" + ruleName + + "' does not exist in the Package '" + + packageName + + "'." ); + } - internalRemoveRule(pkg, rule); + internalRemoveRule(pkg, rule); - pkg.removeRule( rule ); - addReloadDialectDatas( pkg.getDialectRuntimeRegistry() ); - } - }); + pkg.removeRule( rule ); + addReloadDialectDatas( pkg.getDialectRuntimeRegistry() ); + } ); } /** @@ -1750,22 +1597,12 @@ public void run() { */ public void removeRule( final InternalKnowledgePackage pkg, final RuleImpl rule ) { - enqueueModification(new Runnable() { - @Override - public void run() { - internalRemoveRule(pkg, rule); - } - }); + enqueueModification( () -> internalRemoveRule( pkg, rule ) ); } public void removeRules( final InternalKnowledgePackage pkg, final List rules ) { - enqueueModification(new Runnable() { - @Override - public void run() { - internalRemoveRules(pkg, rules); - } - }); + enqueueModification( () -> internalRemoveRules( pkg, rules ) ); } private void internalRemoveRules(InternalKnowledgePackage pkg, List rules) { @@ -1786,89 +1623,63 @@ private void internalRemoveRule(InternalKnowledgePackage pkg, RuleImpl rule) { public void removeFunction( final String packageName, final String functionName ) { - lock(); - try { - final InternalKnowledgePackage pkg = this.pkgs.get( packageName ); - if (pkg == null) { - throw new IllegalArgumentException( "Package name '" + packageName + - "' does not exist for this Rule Base." ); - } - - Function function = pkg.getFunctions().get(functionName); - if (function == null) { - throw new IllegalArgumentException( "function name '" + packageName + - "' does not exist in the Package '" + - packageName + - "'." ); - } + enqueueModification( () -> internalRemoveFunction( packageName, functionName ) ); + } - removeFunction( pkg, - functionName ); - pkg.removeFunction( functionName ); - if (rootClassLoader instanceof ProjectClassLoader) { - ((ProjectClassLoader)rootClassLoader).undefineClass(function.getClassName()); - } + private void internalRemoveFunction( String packageName, String functionName ) { + final InternalKnowledgePackage pkg = this.pkgs.get( packageName ); + if (pkg == null) { + throw new IllegalArgumentException( "Package name '" + packageName + + "' does not exist for this Rule Base." ); + } - addReloadDialectDatas( pkg.getDialectRuntimeRegistry() ); - } finally { - unlock(); + Function function = pkg.getFunctions().get( functionName ); + if (function == null) { + throw new IllegalArgumentException( "function name '" + packageName + + "' does not exist in the Package '" + + packageName + + "'." ); } - } - /** - * Handle function removal. - * - * This method is intended for sub-classes, and called after the - * {@link KieBaseEventListener#beforeRuleRemoved(BeforeRuleRemovedEvent)} before-rule-removed} - * event is fired, and before the function is physically removed from the package. - * - * This method is called with the rulebase lock held. - */ - protected/* abstract */void removeFunction( String functionName ) { - // Nothing in default. - } + this.eventSupport.fireBeforeFunctionRemoved( pkg, functionName ); + pkg.removeFunction( functionName ); + this.eventSupport.fireAfterFunctionRemoved( pkg, functionName ); + if (rootClassLoader instanceof ProjectClassLoader ) { + ((ProjectClassLoader)rootClassLoader).undefineClass(function.getClassName()); + } - /** - * Notify listeners and sub-classes about imminent removal of a function from a package. - * - * This method is called with the rulebase lock held. - */ - private void removeFunction( final InternalKnowledgePackage pkg, - final String functionName ) { - this.eventSupport.fireBeforeFunctionRemoved( pkg, - functionName ); - removeFunction( functionName ); - this.eventSupport.fireAfterFunctionRemoved( pkg, - functionName ); + addReloadDialectDatas( pkg.getDialectRuntimeRegistry() ); } public void addProcess( final Process process ) { // XXX: could use a synchronized(processes) here. - this.eventSupport.fireBeforeProcessAdded(process); lock(); try { - this.processes.put( process.getId(), - process ); + internalAddProcess( process ); } finally { unlock(); } + } + + private void internalAddProcess( Process process ) { + this.eventSupport.fireBeforeProcessAdded(process); + this.processes.put( process.getId(), process ); this.eventSupport.fireAfterProcessAdded(process); } public void removeProcess( final String id ) { + enqueueModification( () -> internalRemoveProcess( id ) ); + } + + private void internalRemoveProcess( String id ) { Process process = this.processes.get( id ); - if (process == null) { + if ( process == null ) { throw new IllegalArgumentException( "Process '" + id + "' does not exist for this Rule Base." ); } - this.eventSupport.fireBeforeProcessRemoved(process); - lock(); - try { - this.processes.remove( id ); - this.pkgs.get(process.getPackageName()).removeRuleFlow(id); - } finally { - unlock(); - } - this.eventSupport.fireAfterProcessRemoved(process); + this.eventSupport.fireBeforeProcessRemoved( process ); + this.processes.remove( id ); + this.pkgs.get( process.getPackageName() ).removeRuleFlow( id ); + this.eventSupport.fireAfterProcessRemoved( process ); } public Process getProcess( final String id ) { @@ -1922,12 +1733,8 @@ public RuleBasePartitionId createNewPartitionId() { return RuleBasePartitionId.createPartition(); } - public FactType getFactType(String packageName, - String typeName) { - return getFactType(packageName + "." + typeName); - } - - public FactType getFactType( final String name ) { + public FactType getFactType(String packageName, String typeName) { + String name = packageName + "." + typeName; readLock(); try { for (InternalKnowledgePackage pkg : this.pkgs.values()) { @@ -1976,7 +1783,7 @@ public boolean removeObjectsGeneratedFromResource(Resource resource) { List functionsToBeRemoved = pkg.removeFunctionsGeneratedFromResource(resource); for (Function function : functionsToBeRemoved) { - removeFunction(function.getName()); + internalRemoveFunction(pkg.getName(), function.getName()); } List processesToBeRemoved = pkg.removeProcessesGeneratedFromResource(resource); diff --git a/drools-core/src/main/java/org/drools/core/impl/StatefulKnowledgeSessionImpl.java b/drools-core/src/main/java/org/drools/core/impl/StatefulKnowledgeSessionImpl.java index 6a48f87bada..b935c17907d 100644 --- a/drools-core/src/main/java/org/drools/core/impl/StatefulKnowledgeSessionImpl.java +++ b/drools-core/src/main/java/org/drools/core/impl/StatefulKnowledgeSessionImpl.java @@ -1194,8 +1194,7 @@ public void setGlobal(final String identifier, this.kBase.readLock(); startOperation(); // Make sure the global has been declared in the RuleBase - final Map globalDefintions = this.kBase.getGlobals(); - final Class type = (Class) globalDefintions.get( identifier ); + Class type = this.kBase.getGlobals().get( identifier ); if ( (type == null) ) { throw new RuntimeException( "Unexpected global [" + identifier + "]" ); } else if ( !type.isInstance( value ) ) { diff --git a/drools-core/src/main/java/org/drools/core/util/BinaryRuleBaseLoader.java b/drools-core/src/main/java/org/drools/core/util/BinaryRuleBaseLoader.java deleted file mode 100644 index b290bc430fb..00000000000 --- a/drools-core/src/main/java/org/drools/core/util/BinaryRuleBaseLoader.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2010 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.drools.core.util; - -import java.io.IOException; -import java.io.InputStream; - -import org.drools.core.definitions.InternalKnowledgePackage; -import org.drools.core.impl.InternalKnowledgeBase; -import org.drools.core.impl.KnowledgeBaseFactory; -import org.kie.api.KieBase; - -/** - * This loads up rulebases from binary packages. - * Can work with an existing or a new rulebase. - * This is useful for deployment. - */ -public class BinaryRuleBaseLoader { - - private InternalKnowledgeBase kBase; - private ClassLoader classLoader; - - /** - * This will create a new default rulebase (which is initially empty). - * Optional parent classLoader for the Package's internal ClassLoader - * is Thread.currentThread.getContextClassLoader() - */ - public BinaryRuleBaseLoader() { - this( KnowledgeBaseFactory.newKnowledgeBase(), null ); - } - - /** - * This will add any binary packages to the rulebase. - * Optional parent classLoader for the Package's internal ClassLoader - * is Thread.currentThread.getContextClassLoader() - */ - public BinaryRuleBaseLoader(InternalKnowledgeBase kBase) { - this( kBase, null); - } - - /** - * This will add any binary packages to the rulebase. - * Optional classLoader to be used as the parent ClassLoader - * for the Package's internal ClassLoader, is Thread.currentThread.getContextClassLoader() - * if not user specified. - */ - public BinaryRuleBaseLoader(InternalKnowledgeBase kBase, ClassLoader classLoader) { - if ( classLoader == null ) { - classLoader = Thread.currentThread().getContextClassLoader(); - if ( classLoader == null ) { - classLoader = Thread.currentThread().getContextClassLoader(); - } - } - this.kBase = kBase; - this.classLoader = classLoader; - } - - /** - * This will add the BINARY package to the rulebase. - * Uses the member ClassLoader as the Package's internal parent classLoader - * which is Thread.currentThread.getContextClassLoader if not user specified - * @param in An input stream to the serialized package. - */ - public void addPackage(InputStream in) { - addPackage(in, this.classLoader); - } - - /** - * This will add the BINARY package to the rulebase. - * - * @param in - * An input stream to the serialized package. - * @param classLoader - * used as the parent ClassLoader for the Package's internal - * ClassLaoder - */ - public void addPackage(InputStream in, - ClassLoader classLoader) { - if ( classLoader == null ) { - classLoader = this.classLoader; - } - - try { - - Object opkg = DroolsStreamUtils.streamIn( in, - classLoader ); - - if ( opkg instanceof InternalKnowledgePackage ) { - InternalKnowledgePackage pkg = (InternalKnowledgePackage) opkg; - addPackage( pkg ); - } else if ( opkg instanceof InternalKnowledgePackage[] ) { - InternalKnowledgePackage[] pkgs = (InternalKnowledgePackage[]) opkg; - for ( InternalKnowledgePackage pkg : pkgs ) { - addPackage( pkg ); - } - } else { - throw new IllegalArgumentException( "Can only add instances of org.kie.rule.Package to a rulebase instance." ); - } - - } catch ( IOException e ) { - throw new RuntimeException( e ); - } catch ( ClassNotFoundException e ) { - throw new RuntimeException( e ); - } finally { - try { - in.close(); - } catch ( IOException e ) { - throw new RuntimeException( e ); - } - } - - } - - private void addPackage(InternalKnowledgePackage pkg) { - if ( !pkg.isValid() ) { - throw new IllegalArgumentException( "Can't add a non valid package to a rulebase." ); - } - try { - ((InternalKnowledgeBase)kBase).addPackage(pkg); - } catch ( Exception e ) { - throw new RuntimeException( "Unable to add package to the rulebase.", e ); - } - } - - public KieBase getKnowledgeBase() { - return this.kBase; - } - -} diff --git a/drools-core/src/test/java/org/drools/core/reteoo/test/ReteDslTestEngine.java b/drools-core/src/test/java/org/drools/core/reteoo/test/ReteDslTestEngine.java index 09a3bed7cd9..0a6bc5fd414 100644 --- a/drools-core/src/test/java/org/drools/core/reteoo/test/ReteDslTestEngine.java +++ b/drools-core/src/test/java/org/drools/core/reteoo/test/ReteDslTestEngine.java @@ -273,7 +273,7 @@ private Map createContext(NodeTestCase testCase) { context.put( "ClassFieldAccessorStore", this.reteTesterHelper.getStore() ); - InternalWorkingMemory wm = rbase.newStatefulSession( true ); + InternalWorkingMemory wm = (InternalWorkingMemory) rbase.newKieSession(); context.put( WORKING_MEMORY, wm ); return context; diff --git a/drools-core/src/test/java/org/drools/core/reteoo/test/dsl/ConfigStep.java b/drools-core/src/test/java/org/drools/core/reteoo/test/dsl/ConfigStep.java index 6b92c628f39..0ee0e8d6e32 100644 --- a/drools-core/src/test/java/org/drools/core/reteoo/test/dsl/ConfigStep.java +++ b/drools-core/src/test/java/org/drools/core/reteoo/test/dsl/ConfigStep.java @@ -68,8 +68,7 @@ public void execute(Map context, List args) { KnowledgeBaseImpl rbase = new KnowledgeBaseImpl("ID", conf); BuildContext buildContext = new BuildContext(rbase); - InternalWorkingMemory wm = (InternalWorkingMemory) rbase - .newStatefulSession(true); + InternalWorkingMemory wm = (InternalWorkingMemory) rbase.newKieSession(); // Overwrite values now taking into account the configuration options. context.put(BUILD_CONTEXT, buildContext); diff --git a/drools-core/src/test/java/org/drools/core/rule/RuleTest.java b/drools-core/src/test/java/org/drools/core/rule/RuleTest.java index 23d154b3148..c459ae91e78 100644 --- a/drools-core/src/test/java/org/drools/core/rule/RuleTest.java +++ b/drools-core/src/test/java/org/drools/core/rule/RuleTest.java @@ -16,10 +16,6 @@ package org.drools.core.rule; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.util.Calendar; import java.util.concurrent.TimeUnit; @@ -36,11 +32,13 @@ import org.drools.core.time.impl.PseudoClockScheduler; import org.junit.Test; +import static org.junit.Assert.*; + public class RuleTest { @Test public void testDateEffective() { - WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession(); + WorkingMemory wm = (WorkingMemory) new KnowledgeBaseImpl( "x", null).newKieSession(); final RuleImpl rule = new RuleImpl( "myrule" ); @@ -65,7 +63,7 @@ public void testDateEffective() { @Test public void testDateExpires() throws Exception { - WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession(); + WorkingMemory wm = (WorkingMemory) new KnowledgeBaseImpl("x", null).newKieSession(); final RuleImpl rule = new RuleImpl( "myrule" ); @@ -88,7 +86,7 @@ public void testDateExpires() throws Exception { @Test public void testDateEffectiveExpires() { - WorkingMemory wm = new KnowledgeBaseImpl("x",null).newStatefulSession(); + WorkingMemory wm = (WorkingMemory) new KnowledgeBaseImpl("x",null).newKieSession(); final RuleImpl rule = new RuleImpl( "myrule" ); @@ -117,7 +115,7 @@ public void testDateEffectiveExpires() { @Test public void testRuleEnabled() { - WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession(); + WorkingMemory wm = (WorkingMemory) new KnowledgeBaseImpl("x", null).newKieSession(); final RuleImpl rule = new RuleImpl( "myrule" ); rule.setEnabled( EnabledBoolean.ENABLED_FALSE ); @@ -137,7 +135,7 @@ public void testRuleEnabled() { public void testTimeMachine() { SessionConfiguration conf = SessionConfiguration.newInstance(); conf.setClockType( ClockType.PSEUDO_CLOCK ); - WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession(conf, null); + WorkingMemory wm = (WorkingMemory) new KnowledgeBaseImpl("x", null).newKieSession(conf, null); final Calendar future = Calendar.getInstance(); ((PseudoClockScheduler)wm.getSessionClock()).setStartupTime( future.getTimeInMillis() ); diff --git a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/command/KBuilderBatchExecutionPersistenceTest.java b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/command/KBuilderBatchExecutionPersistenceTest.java deleted file mode 100644 index bc1f4100a60..00000000000 --- a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/command/KBuilderBatchExecutionPersistenceTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -package org.drools.persistence.command; - -import org.drools.compiler.command.KBuilderBatchExecutionTest; -import org.drools.core.impl.KnowledgeBaseFactory; -import org.drools.persistence.util.DroolsPersistenceUtil; -import org.junit.After; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.kie.api.KieBase; -import org.kie.api.runtime.Environment; -import org.kie.api.runtime.EnvironmentName; -import org.kie.api.runtime.KieSessionConfiguration; -import org.kie.internal.persistence.jpa.JPAKnowledgeService; -import org.kie.internal.runtime.StatefulKnowledgeSession; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; - -import static org.drools.persistence.util.DroolsPersistenceUtil.DROOLS_PERSISTENCE_UNIT_NAME; -import static org.drools.persistence.util.DroolsPersistenceUtil.OPTIMISTIC_LOCKING; -import static org.drools.persistence.util.DroolsPersistenceUtil.PESSIMISTIC_LOCKING; -import static org.drools.persistence.util.DroolsPersistenceUtil.cleanUp; -import static org.drools.persistence.util.DroolsPersistenceUtil.createEnvironment; - -@RunWith(Parameterized.class) -public class KBuilderBatchExecutionPersistenceTest extends KBuilderBatchExecutionTest { - - private Map context; - private boolean locking; - - @Parameters(name="{0}") - public static Collection persistence() { - Object[][] locking = new Object[][] { - { OPTIMISTIC_LOCKING }, - { PESSIMISTIC_LOCKING } - }; - return Arrays.asList(locking); - }; - - public KBuilderBatchExecutionPersistenceTest(String locking) { - this.locking = PESSIMISTIC_LOCKING.equals(locking); - } - - @After - public void cleanUpPersistence() throws Exception { - disposeKSession(); - cleanUp(context); - context = null; - } - - protected StatefulKnowledgeSession createKnowledgeSession(KieBase kbase) { - if( context == null ) { - context = DroolsPersistenceUtil.setupWithPoolingDataSource(DROOLS_PERSISTENCE_UNIT_NAME); - } - KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); - Environment env = createEnvironment(context); - if( this.locking ) { - env.set(EnvironmentName.USE_PESSIMISTIC_LOCKING, true); - } - return JPAKnowledgeService.newStatefulKnowledgeSession(kbase, ksconf, env); - } - -}