Permalink
Browse files

- Initial implementation of dynamic resource addition

  • Loading branch information...
esteban-aliverti committed Jul 26, 2012
1 parent 191a89e commit b38e0043794d35932bfdd6e6e232a7f84a9109e8
@@ -38,6 +38,7 @@
import org.drools.management.DroolsManagementAgent;
import org.drools.mas.AgentID;
import org.drools.mas.util.helper.SessionLocator;
+import org.drools.runtime.Globals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -101,17 +102,23 @@ public DroolsAgent spawn( DroolsAgentConfiguration config ) {
logger.debug( " ### Creating Agent Sub-Sessions " );
}
-
+ mind.setGlobal( "grid", grid );
for ( DroolsAgentConfiguration.SubSessionDescriptor descr : config.getSubSessions() ) {
if ( logger.isDebugEnabled() ) {
logger.debug( " ### Creating Agent Sub-Session: " + descr.getSessionId() + "- CS: " + descr.getChangeset() + " - on node: " + descr.getNodeId() );
}
SessionManager sm = SessionManager.create( config, descr, grid, true );
StatefulKnowledgeSession mindSet = sm.getStatefulKnowledgeSession();
+ try{
+ mindSet.setGlobal( "grid", grid );
+ } catch (Exception e){
+ //maybe 'grid' is not even defined in subsession
+ logger.debug("Global 'grid' not set on session '"+descr.getSessionId()+"' due to "+e.getMessage());
+ }
+
mindSet.fireAllRules();
-
- mind.setGlobal( "grid", grid );
+
mindSet.insert( new SessionLocator( config.getMindNodeLocation(), config.getAgentId(), true, false ) );
mindSet.insert( new SessionLocator( descr.getNodeId(), descr.getSessionId(), false, true ) );
mind.insert( new SessionLocator( descr.getNodeId(), descr.getSessionId(), false, true ) );
@@ -125,7 +132,11 @@ public DroolsAgent spawn( DroolsAgentConfiguration config ) {
return new DroolsAgent( grid, aid, mind );
} catch ( Throwable t ) {
- logger.error( "SOMETHING BAD HAPPENED WHILE TRYING TO CREATE AN AGENT " + t.getMessage() + ", due to " + t.getCause().getMessage() );
+ if (t.getCause() != null){
+ logger.error( "SOMETHING BAD HAPPENED WHILE TRYING TO CREATE AN AGENT " + t.getMessage() + ", due to " + t.getCause().getMessage() );
+ }else{
+ logger.error( "SOMETHING BAD HAPPENED WHILE TRYING TO CREATE AN AGENT " + t.getMessage());
+ }
if ( logger.isDebugEnabled() ) {
t.printStackTrace();
}
@@ -33,10 +33,14 @@
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Collection;
+import java.util.Iterator;
import org.apache.commons.io.IOUtils;
import org.drools.conf.AssertBehaviorOption;
+import org.drools.definition.KnowledgePackage;
+import org.drools.definitions.impl.KnowledgePackageImp;
import org.drools.grid.helper.GridHelper;
import org.drools.grid.service.directory.WhitePages;
+import org.drools.io.ResourceFactory;
import org.drools.io.impl.UrlResource;
import org.drools.io.internal.InternalResource;
import org.drools.xml.ChangeSetSemanticModule;
@@ -258,6 +262,7 @@ public static void addResource( Grid grid, String nodeId, String sessionId, Stri
+ "</add>"
+ "</change-set>"
+ "";
+
Resource changeSetRes = new ByteArrayResource( changeSetString.getBytes() );
((InternalResource) changeSetRes).setResourceType( ResourceType.CHANGE_SET );
//resources.put(id, res);
@@ -311,4 +316,26 @@ private static GridNode createLocalNode( Grid grid, String nodeName ) {
GridNode localNode = grid.createGridNode( nodeName );
return localNode;
}
+
+ public static void addResource( WorkingMemory ksession, ResourceDescriptor rd){
+ KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+ kbuilder.add(ResourceFactory.newUrlResource(rd.getResourceURL()), rd.getType());
+
+ if (kbuilder.hasErrors()){
+ Iterator<KnowledgeBuilderError> iterator = kbuilder.getErrors().iterator();
+ while (iterator.hasNext()) {
+ KnowledgeBuilderError knowledgeBuilderError = iterator.next();
+ logger.debug( " ### Session Manager: Error compiling resource '"+rd.getResourceURL()+"': " + knowledgeBuilderError.getMessage() );
+ }
+ }
+
+ org.drools.rule.Package[] packages = new org.drools.rule.Package[kbuilder.getKnowledgePackages().size()];
+ int i=0;
+ for (KnowledgePackage knowledgePackage : kbuilder.getKnowledgePackages()) {
+ packages[i++] = ((KnowledgePackageImp)knowledgePackage).pkg;
+ }
+
+ ksession.getRuleBase().addPackages(packages);
+
+ }
}
@@ -33,8 +33,16 @@ import org.drools.grid.Grid;
import org.drools.grid.api.impl.ResourceDescriptorImpl;
import org.drools.grid.api.ResourceDescriptor;
+import java.net.URL;
+import org.drools.builder.ResourceType;
+
global Grid grid;
+declare ResourceAdditionRequest
+ URL: URL
+ type: ResourceType
+end
+
query queryIf( Object $o )
$queryIf : Object( this == $o )
end
@@ -69,5 +77,21 @@ end
//end
+rule "Add Resource"
+when
+ $rar: ResourceAdditionRequest($url: URL, $type: type)
+ SessionLocator( $nodeId: nodeId, $sessionId : sessionId, mind == false )
+then
+ LoggerHelper.error("Loading resource '" + $rar.getURL() +"' in session '"+$sessionId+"' of grid '"+grid+"'");
+
+ ResourceDescriptorImpl rd = new ResourceDescriptorImpl( );
+ rd.setResourceURL($url);
+ rd.setType($type);
+ //SessionManager.addResource(grid, $nodeId, $sessionId, rd);
+
+ SessionManager.addResource(drools.getWorkingMemory(), rd);
+
+ retract($rar);
+end
@@ -0,0 +1,78 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package mock;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+import org.drools.builder.ResourceType;
+
+/**
+ *
+ * @author esteban
+ */
+public class ClasspathURLResourceLocator implements Serializable{
+
+ /**
+ * patient name used for routing
+ */
+ private String name;
+
+ private String URL;
+ private ResourceType resourceType;
+
+ /** A {@link URLStreamHandler} that handles resources on the classpath. */
+ public class ClasspathURLHandler extends URLStreamHandler {
+ /** The classloader to find resources from. */
+ private final ClassLoader classLoader;
+
+ public ClasspathURLHandler() {
+ this.classLoader = getClass().getClassLoader();
+ }
+
+ public ClasspathURLHandler(ClassLoader classLoader) {
+ this.classLoader = classLoader;
+ }
+
+ @Override
+ protected URLConnection openConnection(URL u) throws IOException {
+ final URL resourceUrl = classLoader.getResource(u.getPath());
+ return resourceUrl.openConnection();
+ }
+ }
+
+ public ClasspathURLResourceLocator(String URL, ResourceType resourceType) {
+ this.URL = URL;
+ this.resourceType = resourceType;
+ }
+
+ public URL getURL() throws MalformedURLException {
+ return new URL(null, URL, new ClasspathURLHandler());
+ }
+
+ public void setURL(String URL) {
+ this.URL = URL;
+ }
+
+ public ResourceType getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(ResourceType resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
@@ -35,6 +35,8 @@
import org.junit.*;
import java.util.*;
+import mock.ClasspathURLResourceLocator;
+import org.drools.builder.ResourceType;
import org.drools.mas.ACLMessage;
import org.drools.mas.Act;
import org.drools.mas.Encodings;
@@ -584,4 +586,43 @@ public void testQueryRefFailure() throws InterruptedException {
assertEquals( Act.FAILURE, ans.get(1).getPerformative() );
}
+
+ @Test
+ public void testDynamicResourceAddition() throws Exception{
+
+ StatefulKnowledgeSession target = mainAgent.getInnerSession("session1");
+
+ for (Object o : target.getObjects()) {
+ System.err.println("\t Assets BEFORE the inform : " + o);
+ }
+
+ Assert.assertFalse(target.getObjects().contains("--------@@ It's alive!! @@--------------"));
+
+ Assert.assertNull(target.getKnowledgeBase().getRule("org.drools.mas.test", "Test this"));
+
+ ClasspathURLResourceLocator uRLResourceLocator = new ClasspathURLResourceLocator(
+ "classpath:newResource.drl",
+ ResourceType.DRL
+ );
+ uRLResourceLocator.setName("patient1");
+
+ ACLMessageFactory factory = new ACLMessageFactory(Encodings.XML);
+ ACLMessage info = factory.newInformMessage("me", "you", uRLResourceLocator);
+ mainAgent.tell(info);
+
+ waitForAnswers( info.getId(), 0, 250, 50 );
+
+ for (Object o : target.getObjects()) {
+ System.err.println("\t Assets AFTER the inform : " + o);
+ }
+
+ //This string comes from newResource.drl
+ Assert.assertTrue(target.getObjects().contains("--------@@ It's alive!! @@--------------"));
+ Assert.assertNotNull(target.getKnowledgeBase().getRule("org.drools.mas.test", "Test this"));
+
+
+
+ }
+
+
}
@@ -0,0 +1,9 @@
+package org.drools.mas.test
+
+rule "Test this"
+when
+then
+ String s = "--------@@ It's alive!! @@--------------";
+ System.out.println("\n\n\t\t"+s+"\n\n");
+ insert(s);
+end
@@ -19,8 +19,11 @@ package org.drools.test;
import mock.MockFact;
import org.slf4j.Logger;
import org.drools.mas.util.LoggerHelper;
+import org.drools.mas.ResourceAdditionRequest;
-
+import java.net.URL;
+import org.drools.builder.ResourceType;
+import mock.ClasspathURLResourceLocator;
query ageOfPatient( MockFact $mock, String $patientName, int $age )
$mock := MockFact( $patientName := name, $age := age )
@@ -33,6 +36,17 @@ then
LoggerHelper.info(" >>> SESSION #1 >>> " + $o);
end
+rule "Add new Resource"
+when
+ ClasspathURLResourceLocator($url: URL, $resourceType: resourceType)
+then
+ LoggerHelper.info(" >>> SESSION #1 >>> URLResourceLocator");
+ ResourceAdditionRequest rar = new ResourceAdditionRequest();
+ rar.setURL($url);
+ rar.setType($resourceType);
+
+ insert (rar);
+end
query exceptional( )
end
@@ -66,7 +66,7 @@ rule "Route_Encoded_X"
salience -1
when
$msg : ACLMessage( $msgId : id, $b : body, encoding == Encodings.XML )
- $patientId : String( this != null ) from InspectMessageHelper.inspect($msg,"//name")
+ $patientId : String( this != null ) from InspectMessageHelper.inspect($msg,"//name[1]")
// mapSession( $patientId , $sessionId ; )
then
LoggerHelper.debug(" ### Example CBR: Routing message X " + $msgId );

0 comments on commit b38e004

Please sign in to comment.